List comprehension

2 snippets in Python

PYPython

List Comprehensions

PY · Lists
syntax
[expression for item in iterable if condition]
example
prices = [10, 25, 50, 75, 100]
affordable = [p for p in prices if p <= 50]
print(affordable)

squares = [n ** 2 for n in range(1, 6)]
print(squares)
output
[10, 25, 50]
[1, 4, 9, 16, 25]

Note Comprehensions are more Pythonic and faster than equivalent for-loop-with-append patterns. Keep them simple; if nesting gets deep, use a regular loop.

List Comprehensions (Detailed)

PY · Comprehensions & Generators
syntax
[expr for x in iterable if cond]
example
# Transform + filter
temps_f = [32, 68, 95, 104, 50]
warm_c = [(f - 32) * 5 / 9 for f in temps_f if f > 60]
print([round(c, 1) for c in warm_c])

# Nested comprehension (flatten)
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [n for row in matrix for n in row]
print(flat)
output
[20.0, 35.0, 40.0]
[1, 2, 3, 4, 5, 6]

Note In nested comprehensions, the outer loop comes first: [x for row in matrix for x in row]. This matches the order of equivalent nested for loops.