Sub topic 3
Tuples: Fixed Records and Unpacking
This chapter assumes you know basic Python syntax (variables, loops, functions), the built-in types int, str, and bool, and the basics of lists, including indexing and slicing. You also need to run Python 3 in a REPL or a script. Here you will learn what a tuple is and when it fits better than a list. You will also learn to use unpacking, which is the feature that makes tuples pleasant to work with.
What a tuple is
A tuple is an ordered, immutable sequence. Ordered means each item has a position. Immutable means that once the tuple exists, you cannot add, remove, or replace its items. Lists are also ordered, but you can change them in place.
You usually create a tuple with commas. The parentheses are mostly there for readability and grouping.
empty = ()
single = (42,)
not_a_tuple = (42)
pair = 1, 2
from_list = tuple([1, 2, 3])
print(type(single), type(not_a_tuple), type(pair))
print(from_list)
print(tuple("abc"))The output is:
<class 'tuple'> <class 'int'> <class 'tuple'>
(1, 2, 3)
('a', 'b', 'c')(42) is just the integer 42 in parentheses. A one-item tuple needs a trailing comma: (42,). This is the most common tuple syntax mistake. The tuple() constructor accepts any iterable and builds a tuple from its items.
Reading from a tuple
Tuples support the read-only parts of the sequence interface you know from lists: indexing, negative indexes, slicing, len, in, iteration, count, and index.
employee = ("Ana", "Engineering", 52000)
print(employee[0]) # Ana
print(employee[-1]) # 52000
print(employee[1:]) # ('Engineering', 52000)
print(len(employee)) # 3
print("Engineering" in employee) # True
print(employee.index("Engineering")) # 1
print(employee.count("Ana")) # 1Slicing a tuple returns a new tuple. Tuples have only two methods, count and index, because every other list method (append, sort, remove) changes the object.
Assigning to an item fails:
employee = ("Ana", "Engineering", 52000)
try:
employee[2] = 55000
except TypeError as e:
print(e) # 'tuple' object does not support item assignmentTo get a "changed" tuple, build a new one. Concatenation with + and slicing both return new tuples:
employee = ("Ana", "Engineering", 52000)
raised = employee[:2] + (55000,)
print(raised) # ('Ana', 'Engineering', 55000)
print(employee) # ('Ana', 'Engineering', 52000)The original is untouched. If you find yourself rebuilding tuples in a loop, you probably wanted a list.
Tuples as fixed records
The main reason to choose a tuple is intent. A tuple says that this group of values forms one unit with a fixed shape. A list says this is a collection of similar things whose length may change.
Compare these two values:
("Ana", "Engineering", 52000)is a record. Position 0 is a name, position 1 is a department, and position 2 is a salary. The items have different types and different meanings.[52000, 48000, 61000]is a collection of salaries. Each item means the same kind of thing, and you can add or remove items freely.
Tuples fit records such as a point (x, y), an RGB color (255, 128, 0), a database row, or the (key, value) pairs that dict.items() produces. Because a tuple cannot change, you can pass it to other code without worrying that the code will alter it.
The cost is that positions carry the meaning, and employee[2] does not say "salary". For records with more than a few fields, collections.namedtuple lets you name the fields. It appears in the last chapter of this tutorial.
Unpacking
Unpacking assigns the items of a sequence to several names in one statement. It works with tuples, lists, strings, and any other iterable. Tuples are its most common source.
employee = ("Ana", "Engineering", 52000)
name, dept, salary = employee
print(name, dept, salary) # Ana Engineering 52000This reads better than employee[0], employee[1], and employee[2], because each name documents its meaning.
Swapping and parallel assignment
The right side of an assignment is evaluated completely before any name on the left is bound. A swap therefore needs no temporary variable:
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1Here b, a is built as a tuple (2, 1) first, then unpacked into a and b.
The count must match
The number of names must equal the number of items. Otherwise Python raises ValueError:
try:
x, y = (1, 2, 3)
except ValueError as e:
print(e) # too many values to unpack (expected 2)
try:
x, y, z = (1, 2)
except ValueError as e:
print(e) # not enough values to unpack (expected 3, got 2)This strictness is useful. If a function starts returning a different number of values, the failure is loud and immediate instead of silent.
Collecting the rest with a starred name
One target may carry a *. It collects all the items not matched by the other names. The starred target is always a list, even when the source is a tuple, and it may be empty:
first, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last) # 1 [2, 3, 4] 5
head, *tail = ("only",)
print(head, tail) # only []You may use at most one starred target in a single unpacking.
Ignoring values
By convention, the name _ marks a value you do not need:
record = ("Ana", "Engineering", 52000)
name, _, salary = record
print(name, salary) # Ana 52000_ is an ordinary variable name. The convention only tells readers you are ignoring that value. With the starred form, first, *_ = items discards everything after the first item.
Nested unpacking
The target can mirror the structure of the data, using parentheses for inner tuples:
segment = ((0, 0), (3, 4))
(x1, y1), (x2, y2) = segment
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(distance) # 5.0Unpacking in loops
A for loop assigns each item to its target, and the target can be an unpacking pattern. This is the usual way to iterate over pairs:
rows = [("ana", 31), ("ben", 27)]
for name, age in rows:
print(name, age)
users = {"ana": 31, "ben": 27}
for name, age in users.items():
print(name, age)
for i, (name, age) in enumerate(rows, start=1):
print(i, name, age)dict.items() yields (key, value) tuples. enumerate yields (index, item) tuples. Parentheses around (name, age) are needed in the last loop because the item is itself a tuple inside the (index, item) pair.
Returning several values from a function
A Python function returns one object. When you write return a, b, that object is a tuple. The caller unpacks it:
def min_max(values):
return min(values), max(values)
low, high = min_max([4, 9, 2])
print(low, high) # 2 9
result = min_max([4, 9, 2])
print(result) # (2, 9)
print(type(result)) # <class 'tuple'>This approach is fine for two or three values whose order is obvious. Beyond that, callers have to remember which position means what, so a namedtuple, a dict, or a small class is clearer.
The same mechanism works in the other direction. A parameter written *args collects extra positional arguments into a tuple:
def show(*args):
print(type(args), args)
show(1, "a") # <class 'tuple'> (1, 'a')Calling show(*some_list) does the reverse and spreads the items of any iterable into separate arguments.
Comparing and sorting tuples
Tuples compare item by item from the left, like words in a dictionary. The first position where two tuples differ decides the result:
print((1, 2) == (1, 2)) # True
print((1, 2) < (1, 3)) # True
print((2, 0) < (1, 99)) # False
print((1, 2) < (1, 2, 0)) # True, because a shorter prefix sorts firstThis makes tuples natural sort keys for sorting by several criteria. The next example sorts by age first, then by name:
people = [("Ben", 27), ("Ana", 31), ("Cy", 27)]
ordered = sorted(people, key=lambda p: (p[1], p[0]))
print(ordered) # [('Ben', 27), ('Cy', 27), ('Ana', 31)]Comparison only works when the items at the deciding position can be compared with each other. (1, "a") < ("b", 2) raises TypeError, because Python would compare 1 with "b".
What immutability does and does not give you
A tuple always holds the same objects in the same positions. It does not make the objects themselves immutable. If an item is a list, you can still change that list through the tuple. The "Pitfalls" chapter covers this with examples.
Two related properties come up in later chapters:
- A tuple is hashable only if all of its items are hashable. That is why tuples of numbers and strings can serve as dict keys and set elements, and tuples containing lists cannot. The "Why some objects can be keys" and "Frozensets and tuples as composite keys" chapters cover this.
- Tuples are usually a little smaller in memory and a little faster to create than equivalent lists, because the size is fixed and Python can skip the spare capacity lists keep for growth. This rarely decides a design, so choose on meaning first.
Choosing a tuple or a list
The diagram shows the questions to ask when you have a sequence of values to store.
In short:
| Situation | Better choice |
|---|---|
| Many similar items, length changes | list |
| A few values of different kinds forming one unit | tuple |
| Values returned together from a function | tuple |
| Composite key for a dict or set | tuple |
| Fixed data that should not be modified by accident | tuple |
Common mistakes with tuples
- Writing
(42)and expecting a tuple. Add the comma:(42,). - Trying to change an item. Build a new tuple, or use a list if you change data often.
- Unpacking with the wrong number of names. Use a starred target when the length varies.
- Expecting
*restto be a tuple. It is always a list. - Packing too many unrelated values into a return tuple. Past three or so, use named fields.
Exercise
What do a and b contain after a, *b = "xyz", and what does x, y = (1,) do?
Show answer
a is 'x' and b is ['y', 'z']. Unpacking works on any iterable, a string here, and the starred target is always a list. x, y = (1,) raises ValueError: not enough values to unpack (expected 2, got 1), because the tuple has one item and two names are given.
Exercise
Given scores = [("Ana", 90), ("Ben", 85), ("Cy", 90)], write one line using sorted that orders them by score from highest to lowest, with ties broken by name from A to Z. What is the result?
Show answer
sorted(scores, key=lambda s: (-s[1], s[0])) returns [('Ana', 90), ('Cy', 90), ('Ben', 85)]. The key is a tuple. Negating the score reverses the numeric order, and the name breaks ties in normal order.
Exercise
A function contains return 5, 10. What type does a call to it give back, and how can the caller assign the two values to separate names?
Show answer
It returns the tuple (5, 10). The caller unpacks it with first, second = func().