A tuple represents a sequence of any objects separated by commas and enclosed in parentheses. A tuple is an immutable object, which means it cannot be changed, and we use it to represent fixed collections of items.
Creating a Tuple
Creating a tuple is very similar to creating a list, unlike the lists where the values are enclosed with in the brackets, tuples use parenthesis.
week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
print(week)
Output:
('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
Accessing items in a Tuple
You can access an item in a tuple in the same way you do with lists:
week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
print(week[1]) # Prints Monday
Similar to list, we can also use negative indexes for accessing the elements from reverse order.
week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
print(week[-1]) # Prints Saturday
Looping through a Tuple
Here is how to iterate through a tuple:
week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
for day in week:
print(day)
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Check if Item Exists in Tuple
You can check if an item exists in a tuple like this:
week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
print("Monday" in week)
print("Sat" in week)
Output:
True
False
Tuple Length
Get the length of a tuple using the built-in len
function:
week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
print(len(week))
Output:
7
Combine Multiple Tuples
Even though tuples are immutable, you can still combine them to create a third entirely new tuple. This is how:
na = ("USA", "Canada", "Mexico")
eu = ("UK", "France", "Germany")
countries = na + eu
print(countries)
Output:
('USA', 'Canada', 'Mexico', 'UK', 'France', 'Germany')
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:
week = ("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
print(week)
week_list = list(week)
print(week_list)
Output:
('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
The second output enclosed with in the brackets indicate that it is a list and not a tuple!