Collections

Comprehension Patterns

Comprehensions can use multiple for clauses and filters when the shape stays clear.

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')]
[x*2 for x in xs if x > 0]out = []for x in xs: if x > 0: out.append(x*2)
Nested clauses compose left to right; the comprehension is still equivalent to a for-loop with append.

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

See also

Run the complete example

Example code

Expected output

[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
[4, 6, 8]

Execution time appears here after you run the example.