Table of Contents
A tuple in Python is very similar to lists except for one major difference, the items inside are unchangeable, in other words immutable. What this means in practice is that once defined, the list cannot be modified.
Creating a Tuple
Creating a tuple is very similar to creating a list:
PYTHONfruits = ("apples", "bananas", "grapes")
print(fruits)
BASH('apples', 'bananas', 'grapes')
While lists are defined using brackets, tuples use parenthesis.
Accessing items in a Tuple
You can access an item in a tuple in the same way you do with lists:
PYTHONfruits = ("apples", "bananas", "grapes")
print(fruits[1])
BASHbananas
You can also use negative indexes:
PYTHONfruits = ("apples", "bananas", "grapes")
print(fruits[-1])
BASHgrapes
Looping through a Tuple
Here is how to iterate through a tuple:
PYTHONfruits = ("apples", "bananas", "grapes")
for fruit in fruits:
print(fruit)
BASHapples
bananas
grapes
Check if Item Exists in Tuple
You can check if an item exists in a tuple like this:
PYTHONfruits = ("apples", "bananas", "grapes")
print("apples" in fruits)
print("strawberries" in fruits)
BASHTrue
False
Tuple Length
Get the length of a tuple using the built-in len
function:
PYTHONfruits = ("apples", "bananas", "grapes")
print(len(fruits))
BASH3
Combine Multiple Tuples
Even though tuples are immutable, you can still combine them to create a third entirely new tuple. This is how:
PYTHONfruits = ("apples", "bananas", "grapes")
vegetables = ("carrots", "peas", "lettuce")
food = fruits + vegetables
print(food)
BASH('apples', 'bananas', 'grapes', 'carrots', 'peas', 'lettuce')
Converting a Tuple into a List
When the situation arises that you indeed must make changes to the tuple, Python gives you the option to convert it to a list instead. Use the list()
function to do just that:
PYTHONfruits = ("apples", "bananas", "grapes")
fruits_list = list(fruits)
print(fruits_list)
BASH['apples', 'bananas', 'grapes']
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Getting Started with Svelte
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API