List Comprehensions in Python
List comprehensions provide a concise way to construct lists from iterables, combining mapping and filtering in a single expression.
Basic form
[expr for item in iterable]
squares = [n*n for n in range(6)]
With filter
Add an if clause to keep only items matching a condition.
evens = [n for n in range(10) if n % 2 == 0]
Transformations
Apply functions or expressions.
upper = [s.upper() for s in ["a", "b", "c"]]
lengths = [len(s) for s in ["py", "python"]]
Nested comprehensions (flatten)
Comprehensions execute left‑to‑right; use multiple for clauses to flatten.
grid = [[1,2,3], [4,5,6]]
flat = [x for row in grid for x in row] # [1,2,3,4,5,6]
Conditional expression inside
Use a ternary in the expression part for transforms that depend on a condition.
labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
Dict and set comprehensions (related)
index = {s: i for i, s in enumerate(["a","b"])}
uniq = {c for c in "hello"}
Generator expressions (memory‑friendly)
Use parentheses to create a generator for streaming.
total = sum(n*n for n in range(10))
Pitfalls
- Avoid deeply nested comprehensions—prefer named loops for readability
- Don’t leak loop variables in 3.x (comprehension variables are local to the expression)
Summary
- List comprehensions combine map/filter elegantly
- Prefer generator expressions when you don’t need a materialized list