Lesson 17 of 34 · Lists & Tuples
Python List Comprehensions
A huge share of everyday code follows one pattern: take a list, transform or filter each item, and collect the results in a new list. Python has a dedicated, beloved syntax for exactly that — the list comprehension. It's one of the features that makes code feel truly Pythonic.
From loop to comprehension
Here's the classic loop-and-append pattern:
numbers = [1, 2, 3, 4]
doubled = []
for n in numbers:
doubled.append(n * 2)
The same thing as a list comprehension:
doubled = [n * 2 for n in numbers] # [2, 4, 6, 8]
Read it from left to right: "n * 2, for each n in numbers". The expression in front can be anything — a calculation, a method call, an f-string:
names = ["ada", "bo"]
print([name.title() for name in names]) # ['Ada', 'Bo']
print([f"#{n}" for n in range(1, 4)]) # ['#1', '#2', '#3']
Filtering with if
Add an if clause at the end to keep only some items:
scores = [45, 82, 67, 91, 30]
passed = [s for s in scores if s >= 60] # [82, 67, 91]
words = ["fire", "ice", "thunder"]
long_words = [w.upper() for w in words if len(w) > 3] # ['FIRE', 'THUNDER']
Choosing between two values
To transform every item in one of two ways — rather than drop some — put a conditional expression in front of the for:
labels = ["even" if n % 2 == 0 else "odd" for n in range(4)]
# ['even', 'odd', 'even', 'odd']
The position matters: a trailing if filters, while a if condition else b at the front chooses a value for every item.
Nested loops
A comprehension can contain several for clauses. They run in the same order as nested loops would:
pairs = [(x, y) for x in range(2) for y in "ab"]
# [(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]
# The same as:
pairs = []
for x in range(2):
for y in "ab":
pairs.append((x, y))
Any iterable works
Comprehensions accept anything you can loop over — ranges, strings, tuples and more:
vowels = [c for c in "serpent hollow" if c in "aeiou"] # ['e', 'e', 'o', 'o']
squares = [n ** 2 for n in range(5)] # [0, 1, 4, 9, 16]
The loop variable stays private to the comprehension — it doesn't leak into the surrounding code.
Keep it readable
Comprehensions are best when they fit comfortably on one line. If you need several conditions, nested if/else logic or side effects such as printing, a regular for loop is clearer. Clever one-liners that nobody can read are not Pythonic.
Common mistakes
if/elsein the wrong place:[x for x in xs if x > 0 else 0]is aSyntaxError. A choice withelsegoes in front:[x if x > 0 else 0 for x in xs].- Using a comprehension only for side effects:
[print(x) for x in xs]builds a useless list ofNonevalues. Use a loop. - Mixing up the order of nested
forclauses — write them in the same order as the equivalent nested loops.
Assignment
Write three functions, each with a single list comprehension:
squares_of_evens(numbers)returns the squares of the even numbers, in their original order.clean_words(words)returns every word stripped of surrounding whitespace and converted to lowercase. Words that are empty after stripping are left out.flatten(grid)turns a list of lists into a single list, row by row.
squares_of_evens([1, 2, 3, 4, 5, 6]) # [4, 16, 36]
clean_words([" Hiss ", "RATTLE", " "]) # ['hiss', 'rattle']
flatten([[1, 2], [3], [4, 5, 6]]) # [1, 2, 3, 4, 5, 6]Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Transforming collections in other languages
- JavaScript Array map, filter and reduce · JavaScript
- Java Lambdas and Streams Basics · Java
- LINQ in C#: Where, Select, OrderBy, GroupBy and Aggregate · C#
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .