Tuples & unpacking, explained simply
A tuple is like a list that cannot be changed once it is made. You write it with round brackets: spot = (3, 5). It is ideal for values that belong together, like the x and y of a point on a map.
Unpacking lets you pull a tuple apart into separate variables in one go: x, y = spot. The number of names on the left must match the number of values.
Lists of tuples are a handy way to store records, and a for loop can unpack each one as it goes.
Example: Mark the treasure
treasures = [("gold", 2, 4), ("pearl", 6, 1)]
for name, x, y in treasures:
print(f"{name} is at column {x}, row {y}")Output
gold is at column 2, row 4
pearl is at column 6, row 1Try this
- Swap two variables with a, b = b, a.
- Try to change spot[0] and read the error.
- Store three friends as (name, age) tuples and print each one with unpacking.
