Python List Comprehensions, Explained With Examples
A list comprehension builds a new list from an existing iterable in one expression. It replaces the three-line pattern "create an empty list, loop, append" with something that reads like a sentence: [n * n for n in nums] means "n squared, for each n in nums".
The shape
[expression for item in iterable if condition]
- The expression comes first and says what each new element looks like.
- The for clause says where items come from.
- The optional if clause at the end filters: only items for which it is true are kept.
To choose between two values for every item, put a conditional expression in the expression position instead: ["even" if n % 2 == 0 else "odd" for n in nums]. The position matters: a trailing if filters items out, while if ... else at the front transforms every item.
Expected output
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
['odd', 'even', 'odd']
[(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]
{'pen': 1.62, 'book': 12.96}
{2, 3}
91Several for clauses
You can chain for clauses; they nest in the same order as written loops would. [(x, y) for x in range(2) for y in "ab"] runs y fastest, giving the four pairs in the output. Beyond two clauses, an ordinary loop is usually easier to read.
Dict and set comprehensions
The same syntax with braces builds other collections. {key: value for ...} makes a dictionary, as in the price-with-tax example, and {expr for ...} makes a set, which deduplicates automatically: three words with lengths 2, 2 and 3 produce {2, 3}.
Generator expressions
Written with parentheses, or directly inside a function call, a comprehension becomes a generator expression: sum(n * n for n in nums). It produces values one at a time instead of building a list, which saves memory when you only need to consume the values once.
When not to use one
Comprehensions are for building collections. If you are calling a function only for its side effect, such as printing, write a normal for loop. If the comprehension needs more than one condition and a nested loop, a loop with comments is kinder to the next reader.
Common mistakes
- Putting
elseafter a filteringifat the end:[x for x in a if x > 0 else 0]is a syntax error. - Forgetting that a comprehension always creates a new list and leaves the original alone.
Summary
[expr for x in items if cond]maps and filters in one expression.- Use
a if cond else bat the front to transform every item. - Braces give dict or set comprehensions; parentheses give a generator.
Quiz: List comprehensions