DMarlon Studio

Lesson 12 · 12 of 20

Tuples and unpacking · Python

Use Python tuples for data that does not change, and unpack them into several variables at once, even inside a for loop.

Python · Tuples and unpacking in DMarlon Studio: the example's code and its output in the terminal

A tuple is like a list, but between parentheses and impossible to change once it is created. It suits data that belongs together and stays fixed, such as a point (3, 7): you read its values as in a list, point[0] and point[1].

Unpacking hands out the values of a tuple to several variables in one line: x, y = point leaves x = 3 and y = 7. You need as many variables as values; the city works the same way, with name, altitude and population.

The same trick swaps two variables without a spare one: left, right = right, left. Python first builds the tuple on the right and then hands it out.

A list of tuples is very handy for tables. In for medal, runner in podium: each round receives one tuple and unpacks it into medal and runner; {medal:>6} lines up the medals on the right.

Some functions return a tuple. divmod(200, 60) gives the floor division and the remainder at once, (3, 20): 200 seconds are 3 minutes and 20 seconds.

Code · main.py

# A tuple is like a list that cannot change. It uses ( ).point = (3, 7)print("Point:", point)print("x =", point[0], "| y =", point[1])# Unpacking: give each value its own name in one line.x, y = pointprint(f"One step right: ({x + 1}, {y})")# Tuples suit fixed records: name, altitude, population.city = ("Madrid", 667, 3.3)name, altitude, population = cityprint(f"{name}: {altitude} m high, {population} million people")# Swap two variables without a spare one.left, right = "rock", "paper"left, right = right, leftprint("left =", left, "| right =", right)# A list of tuples, unpacked right in the for loop.podium = [("gold", "Ana"), ("silver", "Ben"), ("bronze", "Chloe")]for medal, runner in podium:    print(f"{medal:>6}: {runner}")# A function such as divmod() can return a tuple.minutes, seconds = divmod(200, 60)print(f"200 seconds = {minutes} min {seconds} s")

Output · python3 main.py

Point: (3, 7)
x = 3 | y = 7
One step right: (4, 7)
Madrid: 667 m high, 3.3 million people
left = paper | right = rock
  gold: Ana
silver: Ben
bronze: Chloe
200 seconds = 3 min 20 s

Key points

  • A tuple goes between ( ) and cannot be changed.
  • a, b = some_tuple hands its values out to variables.
  • a, b = b, a swaps two variables.
  • A for loop can unpack each tuple of a list.

Exercise

Make a list of tuples with three cities (name, today's temperature) and print each one with its temperature; then swap the first and the last city.