Tuples and unpacking
Immutable pairs and several values at once.
A tuple is like a list, but immutable. It is written in round brackets: point = (3, 4). You cannot change an element, point[0] = 5 gives a TypeError. You choose a tuple when a set of values belongs together as a whole: coordinates, a "name and age" pair, a row from a table.
A one-element tuple needs a comma: (5,). Without it, (5) is just a number in brackets. It is the comma, not the brackets, that makes a tuple: t = 1, 2 is a tuple too.
Unpacking spreads the elements over names:
point = (3, 4)
x, y = point
first, *rest = [1, 2, 3, 4]
print(x, y, first, rest) # 3 4 1 [2, 3, 4]
The number of names must match the number of elements, otherwise you get a ValueError. A name with an asterisk collects "everything else" into a list. Unpacking works in a loop: for name, age in people: unpacks each pair right away.
A function can return several values; in fact it returns a tuple:
def split_name(full):
first, last = full.split()
return first, last
name, surname = split_name("Ada Lovelace")
Unlike lists, tuples can be dictionary keys and elements of a set, because they do not change. For example, a dictionary keyed by coordinates, {(0, 0): "start"}, is a common technique in grid puzzles.
Practice
An asterisk at the start
What does the program print?
*head, last = [1, 2, 3] print(head)A one-element tuple
Which expression creates a tuple with the single element 5?
- (5,)
- (5)
- [5]
- tuple(5)
Minimum and maximum
Write a function min_max(nums) that returns a tuple of the smallest and the largest number in the list.