Python Access & Unpack Tuples
An index reaches one item in a tuple. Unpacking gives each item in a tuple its own variable in one line.
Reach one item
Indexes work just like they do for lists.
fruit = ("apple", "banana", "cherry")
print(fruit[0])
print(fruit[-1])Slice a tuple
A slice gives you a new, smaller tuple.
numbers = (10, 20, 30, 40, 50)
print(numbers[1:3])
print(numbers[:2])Unpack into variables
One line can give each item its own name.
point = (3, 7)
x, y = point
print(x)
print(y)Collect the rest with a star
A starred name collects the items that are left over.
scores = (95, 80, 70, 60)
first, *rest = scores
print(first)
print(rest)Change means a new tuple
You cannot change a tuple in place. Build a new one instead.
colors = ("red", "green")
colors = colors + ("blue",)
print(colors)Example
record = ("Maya", 88, "A")
name, score, grade = record
print(f"{name} scored {score}")
print(f"Grade: {grade}")Key points
- Use an index in square brackets to reach one item
- Use a slice to get a smaller new tuple
- Unpacking: giving each item in a tuple its own variable in one line
- The number of variables must match the number of items
- Use a starred name like *rest to collect what is left over
In this example, record holds a name, a score, and a grade. The next line unpacks the tuple into three variables. name gets Maya, score gets 88, and grade gets A. The first print uses name and score in an f-string. The second print shows the grade on its own line.
Note
The starred name always collects its items into a list, even when you unpack a tuple.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does this code print? first, *rest = (10, 20, 30)