Python List Comprehensions Explained
List comprehensions build a new list from an iterable in one readable line. Learn the syntax, when to add conditions, and when a loop is clearer.
Published September 17, 2026
A list comprehension builds a new list from an iterable in one readable line: [expression for item in iterable if condition]. It replaces many small for loops with append.
The concept
Read it left to right: for each item in the iterable, optionally keep it if the condition is true, compute the expression, and collect the results into a list.
Comprehensions are usually faster than a manual loop with append, but if the logic needs more than one condition or side effects, a regular loop is clearer.
From loop to comprehension
- Take each number in range(5)
- Filter: keep only the even ones (if n % 2 == 0)
- Transform: square each (n * n)
- Collect into a list: [0, 4, 16]
Practical examples
Basic
squares = [n * n for n in range(5)] # [0, 1, 4, 9, 16]With a filter
evens = [n for n in range(10) if n % 2 == 0]if/else goes before the for
labels = ['even' if n % 2 == 0 else 'odd' for n in range(4)]Nested (flatten a matrix)
matrix = [[1, 2], [3, 4]]
flat = [x for row in matrix for x in row] # [1, 2, 3, 4]Common mistakes
- Putting if/else after the for (a syntax error) — the ternary goes in the expression part.
- Cramming three loops into one line; readability suffers.
- Using a comprehension just for side effects like print().
Key takeaways
- [expr for x in it if cond].
- Ternary else lives in the expression, not at the end.
- Use a loop when it gets complicated.
FAQ
What about memory for huge data?
Use a generator expression with round brackets: (n*n for n in range(10**9)).
Do comprehensions leak the loop variable?
No, in Python 3 the variable is local to the comprehension.