Sub topic 10
Common pitfalls
This chapter covers the mistakes that most often trip up people who already write comprehensions. It assumes you know list, dict, and set comprehensions, the if filter, and basic nested loops. Each pitfall below shows the symptom, the cause, and the fix.
Pitfall 1: `{}` is an empty dict, not an empty set
A set comprehension and a dict comprehension both use curly braces. A literal {} with nothing inside is always a dict. To get an empty set, call set().
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'>This bites when you start with seen = {} and later call seen.add(...). The code fails with an AttributeError because dicts have no add method.
Pitfall 2: duplicate keys silently overwrite
A dict comprehension does not warn you when two items produce the same key. The later item wins and the earlier one is lost. A set comprehension behaves similarly: it keeps one copy of each value.
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" and "cherry" both have length 6. Inverting the mapping keeps only "cherry", because it comes later. If you need every word, group them into lists instead of using one value per key. Also compare len(result) with the length of the input when you expect one entry per item.
Pitfall 3: aliased inner lists
Building a grid with * repeats a reference to one inner list. It does not copy the list. A change through one row then shows up in every row.
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 comprehension evaluates [0] * 3 once per row, so each row is a separate list. The bad version evaluates it once and uses the result twice. The outer * 2 is safe only when the repeated items are immutable, such as numbers or strings.
Pitfall 4: wrong order of `for` clauses
With several for clauses, read them in the same order as the nested loops you would write by hand. The outer loop comes first.
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 for value in row for row in matrix, Python raises a NameError because row does not exist yet when the first clause runs.
Pitfall 5: filter and conditional expression look alike
A trailing if drops items. An if/else before for picks a value for every item. The else is only legal in the second position.
evens = [n for n in range(5) if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(evens) # [0, 2, 4]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']Writing [n for n in range(5) if n % 2 == 0 else 0] is a SyntaxError. If you want a value for every item, move the condition before for.
Pitfall 6: side effects inside a comprehension
A comprehension should build a collection. Calling functions only for their effect, such as print or list.append, produces a throwaway list of None values and hides the real purpose of the code.
names = ["Ada", "Grace"]
# Avoid: builds [None, None] and discards it
[print(name) for name in names]
# Prefer: a plain loop states the intent
for name in names:
print(name)Pitfall 7: expecting the loop variable to leak
In Python 3, the loop variable stays inside the comprehension. Old Python 2 code relied on it leaking out, but you should not expect that now.
x = "outer"
squares = [x * x for x in range(3)]
print(squares) # [0, 1, 4]
print(x) # outerQuick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError: 'dict' object has no attribute 'add'` | `{}` used as an empty set | Use `set()` |
| Dict has fewer entries than expected | Duplicate keys overwrote each other | Group values into lists |
| Changing one row changes all rows | Outer `*` repeated one inner list | Use a comprehension per row |
| `NameError` in a nested comprehension | `for` clauses in the wrong order | Match the nested-loop order |
| `SyntaxError` on `else` | `else` used after a trailing `if` | Move `if`/`else` before `for` |
Exercise
This code is meant to give each of three players their own empty score list, but adding a score for one player changes all of them. Explain why, and fix it. scores = {name: [] for name in ["a", "b", "c"]} works correctly, but row = [[]] * 3; row[0].append(10) does not.
Show answer
[[]] * 3 creates one empty list and repeats a reference to it three times, so all three positions share the same list and append shows up everywhere. Fix it with a comprehension that creates a new list each time: row = [[] for _ in range(3)]. The dict comprehension works because [] is evaluated once per key.
Exercise
What does {len(w): w for w in ["hi", "yo", "hey"]} return, and why?
Show answer
It returns {2: 'yo', 3: 'hey'}. "hi" and "yo" both produce the key 2, so the later item, "yo", overwrites the earlier one.