Collections
Comprehension Patterns
Multiple for clauses behave like nested loops. The leftmost for is the outer loop, and the next for runs inside it.
Source
colors = ["red", "blue"]
sizes = ["S", "M"]
variants = [(color, size) for color in colors for size in sizes]
print(variants)Output
[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]Multiple if clauses filter values. They are useful for simple conditions, but an explicit loop is clearer when the rules need names or explanation.
Source
numbers = range(10)
filtered = [n for n in numbers if n % 2 == 0 if n > 2]
print(filtered)Output
[4, 6, 8]Notes
- Read comprehension clauses from left to right.
- Multiple
forclauses act like nested loops. - Prefer an explicit loop when the comprehension stops being obvious.
See also
- related: Comprehensions
- next depth: Generator Expressions
- prerequisite: For Loops
Run the complete example
Expected output
[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
[4, 6, 8]
Execution time appears here after you run the example.