Lesson 2 of 5 · Collections · 2 min read · Updated
Tuples
Fixed groups of values, unpacking them into names, and when to choose a tuple over a list.
A tuple is like a list written with round brackets — but it cannot be changed after it is made. Use it for values that belong together and stay together: a point's x and y, a date's day, month and year.
point = (3, 4)
print(point[0], point[1])
x, y = point
print(x + y)
single = (5,)
print(type(single), type((5)))
3 4
7
<class 'tuple'> <class 'int'>
x, y = point is unpacking: each value goes into its own name. You have already used it — a, b = b, a swaps two variables by building and unpacking a tuple.
Warning
A one-item tuple needs a comma: (5,). Without it, (5) is just the number 5 in brackets. It is the comma that makes a tuple, not the brackets.
Tuple tools
days = ("Mon", "Tue", "Wed", "Tue")
print(days.count("Tue"), days.index("Wed"))
print(len(days), days[1:3])
first, *rest = [10, 20, 30, 40]
print(first, rest)
2 2
4 ('Tue', 'Wed')
10 [20, 30, 40]
Tuples support indexing, slicing, len(), in, count() and index() — everything that reads, nothing that writes. A starred name such as *rest collects whatever is left over when unpacking.
Note
Because tuples cannot change, they can be dictionary keys and set members, which lists cannot. {(12, 5): "meeting"} works; {[12, 5]: "meeting"} raises a TypeError.
Which of these is a tuple with one item?
Try this now
- Store three students as (name, marks) tuples in a list, then loop and print each with unpacking.
- Use
*middleto pull out everything except the first and last of a list of numbers.
Create a free account to save your progress, or sign in.