Tuples
A tuple is like a list that cannot be changed after it is created. Tuples use round brackets.
Python
point = (3, 4)
colour = (255, 128, 0)
person = ("Asha", 21, "Mumbai")
print(point[0], point[1])
print(person[-1])
print(len(colour))Tuples are immutable
Python
point = (3, 4)
point[0] = 10You can still make a new tuple from an old one: point = (10, point[1]).
Why use a tuple?
- Safety: data that should not change (a date, a coordinate, an RGB colour) cannot be changed by accident.
- Dictionary keys: tuples can be keys in a dictionary; lists cannot.
- Meaning: by convention, a tuple holds a fixed set of different things (name, age, city), while a list holds many things of the same kind.
Packing and unpacking
Writing values separated by commas packs them into a tuple; assigning a tuple to several names unpacks it:
Python
location = 19.07, 72.88 # packing (brackets are optional)
lat, lon = location # unpacking
print(lat, lon)
name, age, city = ("Leo", 30, "London")
print(f"{name} ({age}) lives in {city}")The number of names must match the number of items, unless you use * to collect the rest:
Python
first, *rest = [1, 2, 3, 4, 5]
print(first, rest)
*start, last = "python"
print(start, last)Returning several values
A function can return a tuple, which the caller unpacks. It looks like returning several values at once:
Python
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([7, 2, 9, 4])
print(low, high)A one-item tuple
The comma makes a tuple, not the brackets:
Python
not_a_tuple = (5)
a_tuple = (5,)
print(type(not_a_tuple), type(a_tuple))Tuple methods
Tuples only have two methods, because they cannot change:
Python
grades = ("A", "B", "A", "C", "A")
print(grades.count("A"))
print(grades.index("C"))Finished this lesson?Mark it complete to earn +20 XP and move your progress on.