List Comprehensions
Building lists in a single readable expression instead of a manual loop with .append().
2 min read
A huge share of loops in real Python code follow the same shape: start with an empty list, loop over something, optionally filter, append a transformed value. List comprehensions collapse that pattern into a single line.
The manual version
squares = []
for n in range(10):
squares.append(n ** 2)The comprehension version
squares = [n ** 2 for n in range(10)]Read it as: "n squared, for each n in range(10)" — the expression to build comes first, followed by the loop that drives it. Both versions above produce the exact same list; the comprehension is just a more direct way to say it.
Adding a filter
A comprehension can include an if clause to only include items that match a condition:
evens = [n for n in range(20) if n % 2 == 0]Compare to the manual loop it replaces:
evens = []
for n in range(20):
if n % 2 == 0:
evens.append(n)Transforming while filtering
The two combine naturally — transform an item, but only for the ones that pass a check:
words = ["apple", "sky", "banana", "ok"]
long_words_upper = [w.upper() for w in words if len(w) > 3]
print(long_words_upper) # ['APPLE', 'BANANA']Dictionary and set comprehensions
The same syntax works for building a dict or set instead of a list:
squares_dict = {n: n ** 2 for n in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
unique_lengths = {len(w) for w in words}A dict comprehension needs a key: value pair before the for; a set comprehension looks just like a list comprehension but with {} instead of [].
When a comprehension is the wrong choice
Comprehensions are meant to make code more readable, not less. Once the logic needs multiple conditions, nested loops, or a transformation too complex to read in one line, a regular for loop is the better choice:
# Avoid -- hard to read at a glance
result = [x * y for x in range(10) for y in range(10) if x != y if (x + y) % 2 == 0]
# Prefer -- a plain loop, even though it's longer
result = []
for x in range(10):
for y in range(10):
if x != y and (x + y) % 2 == 0:
result.append(x * y)A good rule of thumb: if you can read the comprehension out loud and it still makes sense as a sentence, keep it. If you have to trace through it mentally like a puzzle, unroll it back into a loop.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.