Skip to content

Tuples

A tuple is an immutable sequence, i.e, a fixed group of values. Members of a tuple usually relate to each other in some way (coordinates, a record in a database table, ...).

A tuple looks like a list but with parentheses (or just commas), and it cannot be changed after creation:

point = (3, 4)
rgb = (255, 128, 0)
single = (42,)           # a one-item tuple NEEDS the trailing comma
also_a_tuple = 1, 2, 3   # parentheses optional — the commas make it

Tuples can be indexed and sliced just like lists:

point[0]         # ⇒ 3
point[0] = 9     # mutation is not allowed
len(point)       # ⇒ 2
3 in point       # ⇒ True

Tuple vs. list — when to use which?

  • Use a list when you want the collection to grow or shrink, or when you need to reorder the items.
  • Use a tuple for a fixed group where position has meaning and the value shouldn't change (a point, an RGB color, a database record, ...)

Packing and unpacking

Packing is synonymous with creating a tuple, either by assigning it to a variable, or returning it from a function.

If you have a tuple, you can assign its items to multiple variables in one step. This is called unpacking:

point = (3, 4)
x, y = point             # x = 3, y = 4

Note that this is works for any sequence:

name, age, city = ("Ada", 36, "London")
first, *rest = [1, 2, 3, 4]     # first=1, rest=[2, 3, 4]

In an unpacking expression, * grabs any remaining items and returns them as a list.

You can swap two values by packing and unpacking in the same assignment statement:

a = 5
b = 6

a, b = b, c             # pack (b, a) then upack into a, b

The built-in enumerate() takes a sequence and returns a new list of tuples, each tuple containing the original item with its position:

names = ['Ada', 'Turing', 'Newman']
list(enumerate(names))                  # ⇒ [(0, 'Ada'), (1, 'Turing'), (2, 'Newman')]

The built-in zip() takes two or more sequences and return a new list of tuples, each tuple containing the items at the same position in the original lists:

scores = [67, 89, 90]
names = ['Alice', 'Eve', 'Bob']
list(zip(names, scores))            # ⇒ [('Alice', 67), ('Eve', 89), ('Bob', 90)]

If the input lists are not of the same length, the length of the resulting list is that of the shortest list.