Sub topic 13
Common errors and pitfalls
This chapter assumes you can create tuples, unpack them into names, use starred targets, and unpack in for loops. It collects the mistakes that come up most often and shows how to read each error message.
Missing commas
A tuple is defined by its commas. (3) is just the integer 3 in parentheses. A trailing comma, as in (3,), makes a one-element tuple. The reverse happens too. A stray comma at the end of an assignment silently creates a tuple.
total = 10,
print(total, type(total))This prints (10,) <class 'tuple'>. If a value is unexpectedly a tuple, look for a trailing comma.
Length mismatches
Unpacking without a starred target needs exactly as many names as items. Python reports which side is wrong.
| Message | Cause |
|---|---|
| `too many values to unpack (expected 2)` | More items than names |
| `not enough values to unpack (expected 3, got 2)` | Fewer items than names |
| `cannot unpack non-iterable NoneType object` | The right side is `None` or another non-iterable |
The last one usually means a function forgot to return a value on some path.
def parse(line):
if ":" in line:
return line.split(":")
try:
key, value = parse("a:b:c")
except ValueError as e:
print(e)
try:
key, value = parse("abc")
except TypeError as e:
print(e)The first call returns a list of three items, so you get the ValueError. The second call returns None, so you get the TypeError. Using line.split(":", 1) limits the result to two parts, and returning a default pair on the other path removes both failures.
Starred target rules
A starred target always produces a list, even when it captures nothing. A statement can have only one starred target, and a starred target cannot stand alone.
first, *rest = (1,)
print(first, rest)
*only, = [1, 2, 3]
print(only)This prints 1 [] and then [1, 2, 3]. Writing *only = [1, 2, 3] without the trailing comma is a SyntaxError. A starred target still needs enough items for the plain names. a, *b, c = [1] raises ValueError.
Unpacking anything iterable
Unpacking works on any iterable, which can hide bugs. A string unpacks into characters, and a dictionary unpacks into its keys.
a, b = "hi"
print(a, b)
d = {"ab": 1, "cd": 2}
for k, v in d:
print(k, v)The loop prints a b and c d. Each key is a two-character string, so it unpacks without error, and the values are never used. Write for k, v in d.items() instead. With one-character keys the same mistake raises a ValueError, which is the safer failure.
Immutability misunderstandings
A tuple cannot rebind its items, but a mutable item can still change. Augmented assignment combines both problems.
t = ([1, 2], 3)
try:
t[0] += [3]
except TypeError as e:
print(e)
print(t)The output is 'tuple' object does not support item assignment followed by ([1, 2, 3], 3). The list was extended in place, and then Python failed when it tried to store the result back into the tuple. The error appears, yet the change happened anyway.
A related error is using a tuple that contains a list as a dictionary key or set member. It raises TypeError: unhashable type: 'list'. A tuple is hashable only if all of its items are.
Checklist
- Check for a missing or stray comma when a value has the wrong type.
- Read whether the message says
ValueError(wrong length) orTypeError(not iterable). - Look for a function path that returns
None. - Use
.items()when looping over dictionary pairs. - Keep mutable objects out of tuples that must stay constant or be hashed.
Exercise
What does a, *b, c = [1, 2] assign to a, b and c, and what happens with a, *b, c = [1]?
Show answer
With two items, a is 1, b is [] and c is 2, because the star may capture zero items. With one item there are not enough values for the two plain names, so Python raises ValueError: not enough values to unpack (expected at least 2, got 1).