Sub topic 10
Common pitfalls
Comprehensions are short, so a mistake in one is easy to miss. Most of these mistakes don't raise an error. The code runs and produces a wrong or surprising result. This chapter covers the mistakes you are most likely to meet, why each happens, and how to fix it.
This chapter assumes you can already write list, dict, and set comprehensions with if filters and if/else expressions. It also assumes you know how nested for clauses read and that a comprehension has its own scope.
A map of the pitfalls
The diagram groups the pitfalls by the symptom you see.
The empty set literal
Braces with nothing inside create an empty dict, not an empty set. This is a historical rule, because {} was a dict literal before sets had literal syntax. A set comprehension is safe because it always contains a for clause. The problem appears when you create an empty set by hand to fill later.
words = ["apple", "banana", "cherry"]
unique_lengths = {len(w) for w in words}
print(unique_lengths) # {5, 6}
empty = set() # {} would create an empty dict, not an empty set
print(type({}), type(empty)) # <class 'dict'> <class 'set'>
nothing = {x for x in []}
print(nothing) # set()The last line shows that a set comprehension over an empty source gives a real empty set, which prints as set().
Aliased inner lists
Multiplying a list repeats references to the same object. If the repeated item is itself a list, every "row" is the same list. A comprehension runs its output expression once per item, so it builds a new inner list each time.
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]The inner [0] * 3 is safe because integers are immutable. Repeating 0 three times can't cause a shared-change bug. The outer * 2 is the dangerous one, because it repeats a mutable list.
The same trap applies to any mutable value you put in the output expression. A comprehension is safe only if the output expression builds a new object on each pass. Writing [row for _ in range(3)], where row was created earlier, gives you three references to one list.
Duplicate keys overwrite earlier ones
A dict comprehension has no warning for duplicate keys. When two items produce the same key, the later one replaces the earlier one. The dict keeps the position of the first insertion but the value of the last.
words = ["apple", "banana", "cherry"]
lengths = {w: len(w) for w in words}
print(lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}
inverted = {length: w for w, length in lengths.items()}
print(inverted) # {5: 'apple', 6: 'cherry'}'banana' is gone from inverted because 'cherry' also has length 6. Inverting a mapping loses data whenever the values are not unique. If you need to keep every item, group them instead. This is a job for a plain loop:
from collections import defaultdict
words = ["apple", "banana", "cherry"]
by_length = defaultdict(list)
for w in words:
by_length[len(w)].append(w)
print(dict(by_length)) # {5: ['apple'], 6: ['banana', 'cherry']}Set comprehensions drop duplicates on purpose, so this is a feature there. It becomes a pitfall when you expect the result to have as many items as the source. len({len(w) for w in words}) is 2, not 3.
Do not rely on set order
A set has no meaningful order. For small integers the printed order often looks sorted, which makes people think it is guaranteed. For strings, the order can change from one run to the next because Python randomizes string hashes. If the order matters, sort at the point where you use the result.
words = ["apple", "banana", "cherry"]
unique_lengths = {len(w) for w in words}
print(sorted(unique_lengths)) # [5, 6]Dicts are different. Since Python 3.7, a dict keeps insertion order, so a dict comprehension produces its keys in the order the source yields them.
Side effects inside a comprehension
A comprehension exists to build a collection. If you use it for its side effects, such as printing, appending to another list, or writing to a file, you also build a throwaway list of whatever those calls return.
log = []
result = [log.append(n) for n in range(3)]
print(result) # [None, None, None]
print(log) # [0, 1, 2]list.append returns None, so result is a list of three None values. The same happens with [print(n) for n in items]. The code works, but it allocates a list nobody wants, and a reader has to work out that you meant a loop. Use a for loop when the goal is an action, not a value.
Side effects are also risky when the order of evaluation matters. A comprehension evaluates items from left to right, but putting a stateful call (a counter, a random number, a network request) in the filter and in the output can run it twice per item. If you need the result of a call in both places, compute it once. The assignment expression covered later in this chapter does that.
Misplaced `if` and `else`
The position of the if decides what it means. Two forms look alike and behave differently.
| Form | Where `if` goes | Meaning | Example |
|---|---|---|---|
| Filter | After the `for` clause | Drops items; no `else` allowed | `[n for n in nums if n > 0]` |
| Conditional expression | Before `for`, in the output | Picks a value for every item; `else` required | `[n if n > 0 else 0 for n in nums]` |
Mixing them up gives a SyntaxError. Writing [n for n in nums else 0] fails because a trailing filter cannot have an else. Writing [n if n > 0 for n in nums] fails because a conditional expression needs an else. Both can appear in one comprehension: [n if n % 2 == 0 else -n for n in nums if n > 0] drops non-positive items and then flips the sign of the odd ones.
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']Wrong order of `for` clauses
Several for clauses read in the same order as the equivalent nested loops, with the outer loop first. People often write them in the order they would say them in English, which reverses them.
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [value for row in matrix for value in row]
print(flat) # [1, 2, 3, 4, 5, 6]
pairs = [(x, y) for x in range(3) for y in range(3) if x < y]
print(pairs) # [(0, 1), (0, 2), (1, 2)]If you write [value for value in row for row in matrix], the first iterable row is looked up before the second for has defined it. You get a NameError. If a variable called row happens to exist in an enclosing scope, there is no error, and the comprehension silently loops over the wrong data. When you are not sure of the order, write the nested loop first and move the clauses into the comprehension without reordering them.
Late binding in closures
A function created inside a comprehension does not copy the loop variable. It looks the variable up when the function is called. By then the loop has finished and the variable holds its last value.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs]) # [0, 1, 2]The second version binds the current value as a default argument, which Python evaluates when the lambda is created. functools.partial also works, and so does a small factory function that takes the value as a parameter.
Generators are lazy and single use
A generator expression looks like a list comprehension with parentheses, but it behaves differently. It yields items one at a time and can be read only once. It is the right tool when you feed the result straight to something like sum, max, or any.
total = sum(n * n for n in range(1_000_000))
print(total) # 333332833333500000The pitfall is to store a generator and read it twice:
gen = (n * n for n in range(3))
print(list(gen)) # [0, 1, 4]
print(list(gen)) # []The second call prints an empty list, and no error is raised. If you need to iterate more than once, or need len() or indexing, build a list. Because evaluation is lazy, errors inside the expression also appear late. With gen = (10 // n for n in [1, 0]), no exception occurs when you create gen. The ZeroDivisionError appears only when something consumes the second item.
Do not turn a list comprehension into a generator to save memory when the next step needs all the items anyway. sorted(n * n for n in data) builds a full list internally either way. The saving is real for sum, any, all, and loops that stop early.
Scope surprises
Python 3 gives each comprehension its own scope, so the loop variable does not overwrite a name outside it.
x = "outer"
squares = [x * x for x in range(3)]
print(squares) # [0, 1, 4]
print(x) # outerThat isolation has two exceptions you should know about.
First, an assignment expression (:=) inside a comprehension binds its target in the surrounding scope, not the comprehension's own scope. It leaks on purpose.
results = [y for n in range(5) if (y := n * n) > 3]
print(results) # [4, 9, 16]
print(y) # 16After the comprehension, y still exists and holds the last value assigned. This is useful for reusing a computed value, but it can overwrite an existing variable named y. Choose names that don't collide with your own. You also cannot use := to rebind the comprehension's own loop variable. That raises a SyntaxError.
Second, inside a class body, a comprehension can see only the first iterable from the class scope. Any other class-level name inside the comprehension fails to resolve.
try:
class Config:
base = 10
values = [base + n for n in range(3)]
except NameError as error:
print(error) # name 'base' is not definedrange(3) works because it is the outermost iterable, which Python evaluates in the class scope. base appears in the output expression, which runs in the comprehension's own scope, and class variables are not visible there. The fix is to move the constant to module level, or to compute the values outside the class body.
A short checklist
Before you commit a comprehension, check these points:
- Is the output a value you will use? If you only want the side effect, write a loop.
- Does the output expression create a fresh object for each item, or does it reuse one mutable object?
- Could two items share a key or value, and would losing one matter?
- Are the
forclauses in the same order as the nested loops you would write by hand? - Will anyone read the result twice? If so, build a list, not a generator.
- Does a lambda or inner function capture the loop variable?
If you answer "yes, and I'm unsure" to more than one, a plain loop is often clearer, and the next chapter covers that decision.
Exercise
A teammate writes seen = {} and then tries seen.add(3) in a loop. It fails with an AttributeError. What is wrong, and what is the fix?
Show answer
{} creates an empty dict, and dicts have no add method. Write seen = set() for an empty set. If the values come from an iterable, a set comprehension such as seen = {n for n in numbers} avoids the problem.
Exercise
What does this print, and how do you change the code so each function returns its own number? funcs = [lambda: n * 10 for n in range(3)] print([f() for f in funcs])
Show answer
It prints [20, 20, 20], because every lambda looks up n after the loop has ended, when n is 2. Bind the value when the lambda is created: funcs = [lambda n=n: n * 10 for n in range(3)], which prints [0, 10, 20].
Exercise
You run names = ["Ann", "Bob", "Cy"] and by_len = {len(s): s for s in names}. The result has two keys, not three. Which names survive, and how would you keep all three?
Show answer
The result is {3: 'Cy'}... wait, check the lengths: "Ann" and "Bob" and "Cy" have lengths 3, 3, and 2, so the result is {3: 'Bob', 2: 'Cy'}. "Ann" is overwritten by "Bob" because both map to key 3. To keep all names, group them with a loop and defaultdict(list), which gives {3: ['Ann', 'Bob'], 2: ['Cy']}.