Sub topic 13
Common Errors and Pitfalls with Tuples and Unpacking
This chapter assumes you can create tuples (including the one-element case), unpack them with plain and starred targets, and use unpacking in for loops and function calls. It collects the mistakes that come up most often. For each one it gives the cause, the error message you will see, and the fix.
Length mismatches
Plain unpacking needs exactly as many targets as there are items. A mismatch raises ValueError, and the message tells you which direction it went wrong.
pair = (1, 2, 3)
try:
a, b = pair
except ValueError as e:
print(e)
try:
a, b, c, d = pair
except ValueError as e:
print(e)
try:
a, *b, c = [1]
except ValueError as e:
print(e)The three messages are too many values to unpack (expected 2), not enough values to unpack (expected 4, got 3) and not enough values to unpack (expected at least 2, got 1). The last one shows that a starred target relaxes the rule only partly. Every non-starred target still needs a value.
A common real-world source is str.split, whose result length depends on the data. "ab".split("=") returns one item, so key, value = line.split("=") fails on any line without an equals sign. Use partition, which always returns exactly three items.
for line in ["name=Ada", "debug"]:
key, sep, value = line.partition("=")
print(repr(key), repr(sep), repr(value))For a line with no =, sep and value are empty strings, so you can test if sep: instead of catching an exception. When you only want the first few items of a longer sequence, write a, b, *_ = values. The name _ is only a convention for "ignored". It still holds a list.
The accidental comma
A comma creates a tuple, so a stray trailing comma changes the type of a value without any error at that line.
total = sum([1, 2, 3]),
print(total, type(total))
label = ("Ada")
print(type(label))
empty = ()
print(type(empty), len(empty))total is (6,), a one-element tuple. The bug usually shows up later, for example as TypeError: unsupported operand type(s) for +: 'tuple' and 'int'. The reverse mistake is ("Ada"), which is just a string in parentheses. The empty tuple () is the one case where parentheses alone make a tuple.
The same rule affects one-element unpacking. (a,) = (1,) and a, = [5] both work, but a = (1,) does not unpack anything.
Unpacking works on any iterable, including strings
The right-hand side of an unpacking can be any iterable, not only a tuple or list. This lets some wrong-type bugs run without an error.
x, y = "hi"
print(x, y)
first, *rest = "hello"
print(first, rest)
d = {"x": 1, "y": 2}
k1, k2 = d
print(k1, k2)The string "hi" splits into two characters, "hello" into five, and the dictionary yields its keys, not its values or pairs. If a function was supposed to return a list of names and returns one string instead, a, b = result succeeds whenever the string happens to have two characters. Use d.items() for key-value pairs. Avoid unpacking a set, because its iteration order is not something to depend on.
The * operator in calls behaves the same way: print(*"abc") prints a b c.
Unpacking also consumes iterators. After a, b = iter([1, 2]) there is nothing left in that iterator. A starred target on an endless iterator, such as first, *rest = itertools.count(), never finishes, because Python must collect every remaining item into the list first.
A starred target is always a list
Whatever you unpack, the starred target receives a list, never a tuple. It can also be empty.
first, *rest = (1, 2, 3)
print(rest, type(rest))
only, *none = (1,)
print(none)
head, *middle, last = (1, 2)
print(middle)
frozen = tuple(rest)
print(frozen)If the result must be hashable, for example because you will use it as a dictionary key, convert it with tuple(rest). Python allows only one starred target in an assignment. Writing a, *b, *c = items is a SyntaxError, because it would be ambiguous where b ends and c begins.
Immutability does not reach inside
A tuple fixes which objects it holds. It does not freeze those objects. The classic surprise is augmented assignment on a mutable item.
t = ([1, 2], 3)
try:
t[0] += [3]
except TypeError as e:
print(e)
print(t)This prints 'tuple' object does not support item assignment and then ([1, 2, 3], 3). The statement t[0] += [3] runs in two steps. First, list.__iadd__ extends the list in place, and that succeeds. Second, Python tries to store the result back into t[0], and that fails. The error is real, but the change has already happened.
Two consequences follow:
- Do not treat a tuple containing lists or dictionaries as a constant. Other code holding a reference to the inner list can change it.
- Repeating a tuple copies references, not objects.
rows = ([],) * 3
rows[0].append("x")
print(rows)All three slots point to the same list, so the output is (['x'], ['x'], ['x']). Build separate lists with tuple([] for _ in range(3)).
Hash failures
A tuple is hashable only if every item inside it is hashable. A tuple containing a list therefore cannot be a dictionary key or set member. The failure appears when the key is used, not when the tuple is created.
rows = [[1, 2], [3, 4]]
seen = set()
for row in rows:
try:
seen.add((row, "tag"))
except TypeError as e:
print(e)
for row in rows:
seen.add((tuple(row), "tag"))
print(sorted(seen))The first loop prints unhashable type: 'list' twice. The second loop converts each inner list with tuple(row) and succeeds. If your data has several levels of nesting, convert every level, not only the outer one.
Evaluation order in multiple assignment
In a, b = b, a, Python evaluates the whole right side first and builds a tuple, then assigns to the targets from left to right. That order is why swaps work. It also means a later target can depend on an earlier one that was just assigned.
a = [0, 0, 0]
i = 0
i, a[i] = 1, 5
print(i, a)You might expect a[0] to be set, but i is assigned first, so a[i] means a[1]. The output is 1 [0, 5, 0]. When a target expression uses a name that is also a target, split the statement into two lines.
The same left-to-right order matters when you rotate references, as in node.next, node = new, node.next. Check that each target is evaluated at the moment you intend.
Concatenation, comparison and parentheses
Three smaller mistakes are worth knowing.
t + 4raisesTypeError: can only concatenate tuple (not "int") to tuple. Writet + (4,), with the comma.- Tuples never equal lists.
(1, 2) == [1, 2]isFalse, even though both hold the same items. A named tuple does equal a plain tuple with the same items, as covered in the previous chapter. - Tuples compare item by item from the left.
(1, 9) < (2, 0)isTruebecause1 < 2decides it. Comparing tuples whose items have incompatible types, such as(1, "a") < (1, 2), raisesTypeError.
Parentheses also change how a call reads. print(1, 2) passes two arguments, while print((1, 2)) passes one tuple.
Diagnosing an unpacking error
When an unpacking line fails, the message points to the cause. The flowchart below follows the checks in a sensible order.
One case in the TypeError branch deserves a note: a function that returns None on some paths. a, b = f() then fails with cannot unpack non-iterable NoneType object. Make every path of the function return the same shape of tuple, or check for None before unpacking.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `too many values to unpack` | More items than targets | Add `*rest` or slice the source |
| `not enough values to unpack` | Fewer items than targets | Use `partition`, check `len`, or fix the source |
| Value is `(6,)` instead of `6` | Trailing comma | Remove the comma |
| `unhashable type: 'list'` | List inside a tuple key | Convert inner lists with `tuple()` |
| Tuple changed and raised an error | `t[0] += ...` on a mutable item | Avoid augmented assignment on tuple items |
| Same list in every slot | `([],) * n` | Use a comprehension to build separate lists |
| Wrong element assigned in a swap | A target depends on an earlier target | Split the statement |
| `cannot unpack non-iterable NoneType` | Function returned `None` | Return a tuple on every path |
Exercise
What does this code print, and why? t = ([1], 2) then try: t[0] += [5] and except TypeError: pass then print(t).
Show answer
It prints ([1, 5], 2). The += on a list extends it in place, which succeeds. Python then tries to rebind t[0], which raises TypeError, but the list has already changed. The except clause hides the error, so the mutation is the only visible effect.
Exercise
A line parser does key, value = line.split("="). It crashes on the lines "mode=fast=slow" and "verbose". Rewrite it so it never raises ValueError, keeps everything after the first = in value, and lets you tell whether an = was present.
Show answer
Use key, sep, value = line.partition("="). For "mode=fast=slow" it gives ("mode", "=", "fast=slow"). For "verbose" it gives ("verbose", "", ""), and sep is empty, so if sep: tells you no = was present. partition always returns exactly three items, so the unpacking cannot fail.
Exercise
You write first, *rest = (10, 20, 30) and want to use rest as a dictionary key. What goes wrong, and what is the fix?
Show answer
rest is the list [20, 30], and lists are unhashable, so using it as a key raises TypeError: unhashable type: 'list'. Convert it first with tuple(rest), which gives (20, 30).