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 is a compact way to build a new list by applying an expression to every item in an iterable, optionally filtering with a condition.
squares = [x * x for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]Steps
- Write the expression to apply to each item first: x * x
- Follow it with 'for x in range(10)' to define the source iterable
- Optionally add 'if x % 2 == 0' at the end to filter which items are included
How it works
List comprehensions are equivalent to a for-loop that appends to a list, but they're generally faster in CPython because the looping happens at the C level rather than through repeated Python-level append() calls.
Things to watch for
- Nesting more than one level of comprehension (or adding multiple conditions) quickly hurts readability — fall back to a regular loop when that happens
- A generator expression (x*x for x in range(10)) uses the same syntax with () instead of [] and is more memory-efficient when you don't need the full list at once
FAQ
When should I use a for-loop instead of a list comprehension?
When the loop body has side effects (like printing or writing to a file) or spans multiple statements — comprehensions are meant for building a list from an expression, not for general-purpose looping.