Python List & Dictionary Comprehensions Tracing
Comprehensions provide concise, expressive syntax for transforming and filtering iterables. Tracing nested loop order inside comprehensions (`for a in X for b in Y`) and ternary conditional placement (`[x if c else y for x in Z]`) is essential for writing functional Python.
Core Conceptual Insights
Theoretical Blueprint:A list comprehension works like an automated factory assembly line: raw items enter from the right (`for x in range()`), pass through inspection filters (`if x % 2 == 0`), get processed (`x * 2`), and drop into a finished list box on the left.
Common Developer Trap:Developers often confuse placing `if` AFTER the loop (`filtering rows out`) versus placing `if / else` BEFORE the loop (`transforming every row via ternary logic`).
Structured Practice Breakdown
Ternary transformation vs trailing filter
res = [x * 2 if x > 0 else 0 for x in [-2, 3, -1, 4] if x % 2 != 0] print(res)
[6, 0]Execution Walkthrough
Trailing `if x % 2 != 0` keeps odd numbers `3` and `-1`. Then `3 > 0` checks True (`3 * 2 = 6`), and `-1 > 0` checks False (`0`). Output: `[6, 0]`.
Nested loop comprehension order
pairs = [f'{i}{j}' for i in ['A', 'B'] for j in [1, 2]]
print(pairs)['A1', 'A2', 'B1', 'B2']Execution Walkthrough
Outer loop iterates `i in ['A', 'B']`. For `i='A'`, `j` iterates `1, 2` (`'A1', 'A2'`). For `i='B'`, `j` iterates `1, 2` (`'B1', 'B2'`).
Dictionary comprehension key overwrite
word = 'level'
d = {ch: i for i, ch in enumerate(word)}
print(d['l'], d['e'])4 3Execution Walkthrough
For `'l'`, `d['l'] = 0` is overwritten later by `d['l'] = 4`. For `'e'`, `d['e'] = 1` is overwritten by `d['e'] = 3`. Output: `4 3`.
Matrix flattening comprehension
matrix = [[10, 20], [30, 40]] flat = [num for row in matrix for num in row] print(flat)
[10, 20, 30, 40]Execution Walkthrough
The outer clause `for row in matrix` iterates each sublist (`[10, 20]`, then `[30, 40]`). The inner clause `for num in row` yields `10, 20, 30, 40` cleanly.