TutreNews Learn

Tuples, copies and choosing the right structure

Tuples and unpacking

Goal: Create tuples, unpack them and return several values from a function · 9 min

A tuple is like a list, but immutable: once created, it cannot be changed. Round brackets: point = (3, 4). A one-item tuple needs a trailing comma: (5,); without it (5) is just the number 5.

Reading works like a list (point[0], slices, len, in), but point[0] = 9 raises a TypeError.

Why use tuples?

  • They signal "this group of values belongs together and will not change" (coordinates, RGB colours, a date).
  • They can be dictionary keys and set members (lists cannot).
  • A function can return several values as a tuple.

Unpacking assigns the items to several names at once:

x, y = point                 # x = 3, y = 4
a, b = b, a                  # swap two variables without a temp
first, *rest = [1, 2, 3, 4]  # first = 1, rest = [2, 3, 4]
def min_max(nums):
    return min(nums), max(nums)   # a tuple
low, high = min_max([4, 9, 2])    # low = 2, high = 9

The number of names must match the number of items (except when using *).

Tuples of pairs work well with loops: for name, score in [("Ada", 90), ("Alan", 85)]:. Convert with tuple(list) and list(tuple).

Worked example: Returning two values

  1. The function returns min and max as one tuple.
  2. Unpack it directly: low, high = min_max(nums).
  3. The same trick swaps variables: a, b = b, a.
def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([4, 9, 2, 7])
print(low, high)
a, b = 1, 2
a, b = b, a
print(a, b)

Output:

2 9
2 1