A tuple is an ordered sequence that cannot be changed after creation. Use parentheses and commas.
point = (3, 5)
colours = ("red", "green", "blue")
single = (42,)
empty = ()The comma creates the tuple. (42) is just the number 42 in parentheses; (42,) is a one-item tuple.
Access and iteration#
point = (3, 5)
print(point[0]) # 3
print(point[-1]) # 5
print(len(point)) # 2
for coordinate in point:
print(coordinate)Slicing works exactly as it does for lists:
numbers = (1, 2, 3, 4, 5)
print(numbers[1:4]) # (2, 3, 4)
print(numbers[::-1]) # (5, 4, 3, 2, 1)Immutability#
point = (3, 5)
point[0] = 7 # TypeError: 'tuple' object does not support item assignmentImmutability makes tuples predictable. They are hashable when all their items are hashable, so they can be dictionary keys or set members:
locations = {
(40.7128, -74.0060): "New York",
(51.5074, -0.1278): "London",
}
print(locations[(51.5074, -0.1278)])A list cannot be used as a dictionary key because it can change.
Unpacking#
point = (3, 5)
x, y = point
print(x, y)The number of names must match the number of items, unless you use a starred target:
first, *middle, last = (1, 2, 3, 4, 5)
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5Unpacking also swaps values without a temporary variable:
a, b = 1, 2
a, b = b, a
print(a, b)Returning multiple values#
A function that returns several values actually returns one tuple:
def min_max(numbers):
return min(numbers), max(numbers)
lowest, highest = min_max([4, 9, 1, 7])
print(lowest, highest)This is idiomatic and readable for small fixed groups. If the result grows beyond a few values, a dictionary or a small class may communicate intent better.
Tuple methods#
Tuples have only two methods:
values = (1, 2, 2, 3)
print(values.count(2)) # 2
print(values.index(2)) # 1Tuple versus list#
Use a tuple when:
- The group has a fixed shape, such as
(latitude, longitude). - The values should not change.
- You need a hashable key for a dictionary or set.
Use a list when:
- You will add or remove items.
- The number of items varies.
- You need methods such as
sort()orappend().
Practice#
Create a tuple for a book's title, author, and year. Unpack it into three variables and print a formatted sentence. Then build a dictionary where each key is a (row, column) tuple and print one entry.
