List Comprehensions
Build a new list in one readable line - transform each item, keep only the ones you want - and know when a plain loop is still better.
What you will be able to do
- Read [expression for item in iterable] as the append loop it replaces
- Turn a loop that builds a list into a comprehension, and back again
- Filter items with an if at the end
- Choose between two values with if/else at the front - and say why the two positions differ
- Use comprehensions with strings, range(), enumerate(), zip() and dict.items()
- Flatten a list of lists and build a grid with nested for clauses
- Explain why a comprehension’s variable does not leak, while a for loop’s does
- Recognise when a plain loop, sum(), any() or all() is the better choice
The idea, in plain English
Lesson 12 showed a pattern you will write again and again: start with an empty list, loop over some items, and append a new value for each one. A list comprehension is that whole pattern in one expression: squares = [n * n for n in numbers].
It does three jobs, in one line: go through every item (for), keep only some of them (if, at the end - optional), and turn each one into a new value (the expression at the front). The result is always a new list; the original is not changed.
Comprehensions are about readability first. One short line that says "the squares of these numbers" is easier to read than four lines of setup. But a comprehension that needs three conditions and two loops is harder to read than the loop it replaced - knowing when to stop is part of the lesson. Every output below comes from running the code in Python 3.14.
Worked example: Turning a four-line append loop into one readable line.
An everyday example: the juice stall
A juice stall has a basket of fruit. The owner makes a jug of juice in three moves:
- Take every fruit from the basket, one at a time.
- Keep only the ripe ones - the rest stay out.
- Squeeze each ripe fruit.
- Everything squeezed goes into a NEW jug. The basket is not changed.
- Said in one sentence: "squeezed fruit, for each fruit in the basket, if it is ripe". That sentence is a list comprehension.
The basketThe iterable you loop over.Each fruit, one at a timeThe for clause.Only the ripe onesThe if clause - at the end, optional.Squeeze itThe expression - at the front.The new jugThe new list that comes back.From loop to comprehension
Every comprehension is a loop you already know how to write. Move the pieces like this:
- The empty list and append() disappear - the square brackets do that job.
- The value you appended moves to the FRONT: n * n.
- The for line follows it, without its colon: for n in numbers.
- Read it as: "n * n, for each n in numbers".
- The front can be any expression - a method call, a calculation, a conversion.
# The loop you already know
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]
# The same list, as a comprehension
squares = [n * n for n in numbers]
print(squares) # [1, 4, 9, 16, 25]
# Any expression can go at the front
names = ["ravi", "kiran", "john"]
print([name.title() for name in names]) # ['Ravi', 'Kiran', 'John']
print([len(name) for name in names]) # [4, 5, 4]
print([n * 1.18 for n in [100, 250]]) # [118.0, 295.0]
print([str(n) for n in numbers]) # ['1', '2', '3', '4', '5']squares = []Gone - the [ ] creates the list.for n in numbers:Becomes the for clause: for n in numbers squares.append(n * n)The value moves to the front: n * nResultsquares = [n * n for n in numbers]Filtering: if at the end
- Add if condition AFTER the for, and only the items where it is true are kept.
- It is the loop’s if, moved to the end: [score for score in scores if score >= 50].
- You can transform and filter at once: the if decides WHICH items, the front decides WHAT each becomes.
- An if at the end has no else - an item is either kept or not.
scores = [45, 82, 67, 91, 38, 74]
# Loop with a filter
passed = []
for score in scores:
if score >= 50:
passed.append(score)
print(passed) # [82, 67, 91, 74]
# The same, as a comprehension: the if goes at the END
passed = [score for score in scores if score >= 50]
print(passed) # [82, 67, 91, 74]
# Transform and filter together: +5 grace marks for those below 50
print([score + 5 for score in scores if score < 50]) # [50, 43]
# Drop empty and blank strings
words = ["apple", "", "banana", " ", "cherry"]
print([w for w in words if w.strip()]) # ['apple', 'banana', 'cherry']
# Conditions combine with and / or
print([n for n in range(1, 21) if n % 3 == 0 and n % 2 == 0]) # [6, 12, 18]Choosing a value: if/else at the front
Sometimes you want to keep EVERY item, but turn it into one of two values. That is a different job, in a different place:
- Put a conditional expression at the front: "pass" if s >= 50 else "fail". (You met this one-line if/else in Lesson 10.)
- Every item stays - the output list has the same length as the input.
- The rule to remember: if at the END filters; if/else at the FRONT chooses.
- You can use both: choose a value at the front, and filter at the end.
- Mix them up and Python stops you before anything runs - see the two errors below.
scores = [45, 82, 67, 91, 38]
# if/else goes at the FRONT - it chooses the value
print(["pass" if s >= 50 else "fail" for s in scores])
# ['fail', 'pass', 'pass', 'pass', 'fail']
# Both together: choose a value, and filter
print(["high" if s >= 80 else "ok" for s in scores if s >= 50])
# ['high', 'ok', 'high']
# Replace negatives with 0, keep the rest
numbers = [-3, 5, -1, 8]
print([n if n > 0 else 0 for n in numbers]) # [0, 5, 0, 8][s for s in [1, 2] if s > 1 else 0]
-> SyntaxError: invalid syntax (an else at the end)
["big" if s > 1 for s in [1, 2]]
-> SyntaxError: expected 'else' after 'if' expression (an if at the front with no else)if at the endFilters. Some items are dropped. No else allowed.if/else at the frontChooses a value. Every item is kept. else is required.Anything you can loop over
A comprehension takes anything a for loop takes (Lesson 12). The everyday ones:
- A string: one character at a time.
- range(): numbers, without writing a list first.
- str.split(): clean each piece of a line of text.
- enumerate(): the position and the value together.
- zip(): two lists side by side.
- dict.items(): each key and value from a dictionary (Lesson 19).
- A list of dictionaries - the shape most API data arrives in.
# Strings are iterable
print([ch for ch in "hello"]) # ['h', 'e', 'l', 'l', 'o']
print([ch.upper() for ch in "python" if ch not in "aeiou"]) # ['P', 'Y', 'T', 'H', 'N']
# range
print([n * n for n in range(1, 6)]) # [1, 4, 9, 16, 25]
# Splitting text, then cleaning each piece
line = " Ravi , Kiran,John , Anil "
print([name.strip() for name in line.split(",")]) # ['Ravi', 'Kiran', 'John', 'Anil']
print([int(x) for x in "10 20 30".split()]) # [10, 20, 30]
# enumerate gives position and value
names = ["Ravi", "Kiran", "John"]
print([f"{i}. {name}" for i, name in enumerate(names, start=1)])
# ['1. Ravi', '2. Kiran', '3. John']
# zip walks two lists side by side
prices = [100, 250, 40]
quantities = [2, 1, 5]
print([p * q for p, q in zip(prices, quantities)]) # [200, 250, 200]
# A dictionary's items
stock = {"pen": 0, "book": 12, "bag": 3, "ink": 0}
print([item for item, count in stock.items() if count == 0]) # ['pen', 'ink']
# A list of dictionaries - the shape APIs return
users = [
{"name": "Ravi", "age": 30, "active": True},
{"name": "Kiran", "age": 17, "active": True},
{"name": "John", "age": 42, "active": False},
]
print([u["name"] for u in users if u["active"]]) # ['Ravi', 'Kiran']
print([u["name"] for u in users if u["age"] >= 18]) # ['Ravi', 'John']Nested loops: flattening and grids
- Two for clauses in one comprehension work like two nested loops.
- They go in the SAME order as the loops: outer first, inner second. [value for row in matrix for value in row].
- That flattens a list of lists into one list, or makes every pair from two lists.
- A comprehension INSIDE another one is different: it builds a list of lists - rows of a grid.
- That is also the fix for Lesson 16’s trap: [[0] * 3] * 3 repeats ONE inner list three times; [[0] * 3 for _ in range(3)] makes three separate lists. (The _ is a name for a loop variable you do not use.)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# The loops
flat = []
for row in matrix:
for value in row:
flat.append(value)
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Same order as the loops: outer for first, inner for second
flat = [value for row in matrix for value in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Every pair
print([(size, colour) for size in ["S", "M"] for colour in ["red", "blue"]])
# [('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]
# A comprehension INSIDE a comprehension builds rows
grid = [[0 for col in range(3)] for row in range(2)]
print(grid) # [[0, 0, 0], [0, 0, 0]]
# Transpose: columns become rows
print([[row[i] for row in matrix] for i in range(3)])
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# The [[0] * 3] * 3 trap from Lesson 16
shared = [[0] * 3] * 3
shared[0][0] = 9
print(shared) # [[9, 0, 0], [9, 0, 0], [9, 0, 0]] - one list, three times
separate = [[0] * 3 for _ in range(3)]
separate[0][0] = 9
print(separate) # [[9, 0, 0], [0, 0, 0], [0, 0, 0]]Tip: Two for clauses is usually the limit for readability. If you need a third, or a condition on each, write the loops out.
The loop variable stays inside
- A comprehension has its own small scope. Its variable exists only inside the brackets.
- So a comprehension cannot overwrite a variable of the same name outside it.
- A for loop is different: after the loop, its variable still holds the last value.
- Try to use a comprehension’s variable afterwards and you get NameError.
x = "outer"
squares = [x * 2 for x in range(3)]
print(squares) # [0, 2, 4]
print(x) # outer - the comprehension's x did not leak out
for n in range(3):
pass
print(n) # 2 - a for loop's variable DOES stay behind
[m for m in range(3)]
print(m) # NameError: name 'm' is not definedWhen NOT to use a comprehension
A comprehension is for BUILDING a list. Use something else when:
- You only want to DO something - print, save, send. [print(n) for n in items] works, but builds a list of None you never use. Write a for loop.
- You only need a total, a yes/no, or the first match. sum(), any(), all() and next() take the same "x for x in items" form without the brackets - no list is built. (This form is a generator expression; Lesson 48 explains it.)
- It needs break, try/except, or several statements per item. A comprehension holds one expression - use a loop.
- It no longer fits on one easy line. If you have to read it twice, the loop was better.
- Speed is not the reason to choose one. On our machine a comprehension took about 91% of the loop’s time - a little faster, but pick it because it is clearer.
# A comprehension used just to print builds a useless list
result = [print(n) for n in [1, 2]]
# 1
# 2
print(result) # [None, None]
# Use a plain loop for actions
for n in [1, 2]:
print(n)
numbers = [4, 8, 15, 16, 23, 42]
# Need only a total, a yes/no, or the first match? You do not need a list.
print(sum(n * n for n in numbers)) # 2854
print(any(n > 40 for n in numbers)) # True
print(all(n > 0 for n in numbers)) # True
print(next((n for n in numbers if n % 5 == 0), None)) # 15import timeit
def with_loop():
result = []
for n in range(1000):
result.append(n * n)
return result
def with_comprehension():
return [n * n for n in range(1000)]
loop = min(timeit.repeat(with_loop, number=2000, repeat=5))
comp = min(timeit.repeat(with_comprehension, number=2000, repeat=5))
print(f"comprehension takes {comp / loop:.0%} of the loop's time")
# Our run (Python 3.14):
# loop: 0.114 s
# comprehension: 0.103 s
# comprehension takes 91% of the loop's timeThe worked example: processing orders
A list of orders, the way an API or a database returns them. Each question is one comprehension:
- Which orders are paid? - filter.
- What are their amounts, and the total? - transform, then sum().
- A label for each large paid order? - transform and filter together.
- Big or small, for every order? - if/else at the front.
- Unique customers in first-seen order? - not a comprehension. "Have I seen this already?" depends on the items before it, so a loop is clearer.
orders = [
{"id": 1, "customer": "Ravi", "amount": 1200, "status": "paid"},
{"id": 2, "customer": "Kiran", "amount": 450, "status": "pending"},
{"id": 3, "customer": "John", "amount": 3000, "status": "paid"},
{"id": 4, "customer": "Anil", "amount": 800, "status": "cancelled"},
{"id": 5, "customer": "Ravi", "amount": 650, "status": "paid"},
]
paid = [o for o in orders if o["status"] == "paid"]
print([o["id"] for o in paid]) # [1, 3, 5]
amounts = [o["amount"] for o in paid]
print(amounts, sum(amounts)) # [1200, 3000, 650] 4850
labels = [f"#{o['id']} {o['customer']}: Rs {o['amount']}" for o in paid if o["amount"] >= 1000]
print(labels) # ['#1 Ravi: Rs 1200', '#3 John: Rs 3000']
print(["big" if o["amount"] >= 1000 else "small" for o in orders])
# ['big', 'small', 'big', 'small', 'small']
# Unique customers, first-seen order: each step depends on the ones before - use a loop
customers = [o["customer"] for o in orders]
unique = []
for c in customers:
if c not in unique:
unique.append(c)
print(unique) # ['Ravi', 'Kiran', 'John', 'Anil']The forms of a list comprehension
Read each one starting from the for.
TransformA new value for every item.
[n * n for n in numbers]
FilterKeep only the items where the condition is true.
[n for n in numbers if n > 0]
Transform + filterKeep some, change those.
[n * n for n in numbers if n > 0]
ChooseEvery item kept, as one of two values.
["+" if n > 0 else "-" for n in numbers]
FlattenTwo for clauses, outer first.
[x for row in matrix for x in row]
GridA comprehension inside a comprehension.
[[0] * 3 for _ in range(3)]
Built-ins that pair with comprehensions
range(start, stop)Numbers to loop over, stop excluded.
[n for n in range(1, 6)]
enumerate(items, start=1)Position and value together.
[f"{i}. {x}" for i, x in enumerate(items, 1)]zip(a, b)Two lists side by side; stops at the shorter.
[p * q for p, q in zip(prices, qty)]
dict.items()Each key and value.
[k for k, v in d.items() if v == 0]
sum() / any() / all()A total or a yes/no - no list needed.
sum(n * n for n in numbers)
next(gen, default)The first match, or the default.
next((n for n in items if n > 5), None)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Take any for loop you wrote in Lessons 12-16 that starts with an empty list and appends. Rewrite it as a comprehension and check both print the same list.”
“Run [s for s in scores if s >= 50], then try ["pass" for s in scores if s >= 50 else "fail"]. Read the error, then fix it by moving if/else to the front.”
“In [value for row in matrix for value in row], swap the two for clauses. What error do you get, and why?”
“Build [[0] * 3] * 3 and [[0] * 3 for _ in range(3)], set [0][0] = 9 in each, and print both.”
“Assign x = "outer", run a comprehension that uses x as its variable, then print x. Do the same with a for loop.”
What usually goes wrong
An if at the end only filters - there is no else there. To choose between two values, the if/else goes at the front.
✗ [s for s in scores if s >= 50 else 0]✓ [s if s >= 50 else 0 for s in scores]The for clauses go in the same order as the nested loops: outer first. Backwards, the inner name is used before it exists.
✗ [value for value in row for row in matrix]✓ [value for row in matrix for value in row]It builds a list nobody uses - [None, None, ...] for print(). Actions belong in a for loop.
✗ [print(name) for name in names]✓ for name in names:
print(name)* repeats a reference to the same inner list, so changing one row changes them all. Build each row with a comprehension.
✗ grid = [[0] * 3] * 3✓ grid = [[0] * 3 for _ in range(3)]sum(), any() and all() take the expression directly. The brackets build a whole list first, for nothing.
✗ total = sum([n * n for n in numbers])✓ total = sum(n * n for n in numbers)Two conditions, two loops and a method call in one comprehension is a puzzle, not a shortcut. Write the loop.
Best practices
- Use a comprehension to BUILD a new list; use a for loop to DO things.
- Keep it to one short line: one for, maybe one if. More than that, write the loop.
- Name the loop variable after one item: [user["name"] for user in users], not [x["name"] for x in y].
- Filter with if at the end; choose a value with if/else at the front.
- Write nested for clauses in loop order: outer first.
- Pass sum(), any() and all() the expression without brackets.
- Build grids with [[0] * n for _ in range(m)], never [[0] * n] * m.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Make a list of the squares of 1 to 10.
Show hintHide hint
range(1, 11) gives 1 to 10.
Show solutionHide solution
print([n * n for n in range(1, 11)])
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]From [12, 7, 30, 15, 8, 21], keep only the even numbers.
Show hintHide hint
A filter at the end: if n % 2 == 0.
Show solutionHide solution
numbers = [12, 7, 30, 15, 8, 21]
print([n for n in numbers if n % 2 == 0]) # [12, 30, 8]From ["ravi", "", "kiran", " ", "john"], make a list of the names in capitals, skipping empty and blank strings.
Show hintHide hint
strip() returns "" for a blank string, and "" is falsy.
Show solutionHide solution
names = ["ravi", "", "kiran", " ", "john"]
print([name.strip().upper() for name in names if name.strip()])
# ['RAVI', 'KIRAN', 'JOHN']Turn the marks [72, 35, 88, 49, 50] into "pass" (50 or more) or "fail" for each one.
Show hintHide hint
Every mark stays, so the if/else goes at the front.
Show solutionHide solution
marks = [72, 35, 88, 49, 50]
print(["pass" if m >= 50 else "fail" for m in marks])
# ['pass', 'fail', 'pass', 'fail', 'pass']Flatten [[1, 2], [3], [4, 5, 6]] into one list.
Show hintHide hint
Two for clauses: the outer list first, then each inner list.
Show solutionHide solution
nested = [[1, 2], [3], [4, 5, 6]]
print([x for group in nested for x in group]) # [1, 2, 3, 4, 5, 6]Rewrite this as one comprehension: start with with_gst = [], loop over prices = [80, 120, 45, 300], and for each price over 100 append round(p * 1.18, 2).
Show hintHide hint
The value you appended goes to the front, the if goes at the end.
Show solutionHide solution
prices = [80, 120, 45, 300]
print([round(p * 1.18, 2) for p in prices if p > 100]) # [141.6, 354.0]A class report in five comprehensions
Each student has a list of marks. Answer every question with one comprehension - and use all(), zip() and a nested for where they fit.
- The average mark of each student, rounded to 1 decimal place.
- The names of the students who scored 40 or more in EVERY subject.
- A grade for each student from their average: A for 85 or more, B for 60 or more, otherwise C.
- Every mark from every student, in one flat list.
- A "Name: grade" line for each student, pairing students with grades using zip().
students = [
{"name": "Ravi", "marks": [78, 85, 92]},
{"name": "Kiran", "marks": [45, 60, 38]},
{"name": "John", "marks": [90, 88, 95]},
{"name": "Anil", "marks": [55, 49, 70]},
]
# 1. Average for each student
# 2. Passed every subject
# 3. Grade for each student
# 4. All marks, flattened
# 5. "Name: grade" lines
Show one solutionHide solution
students = [
{"name": "Ravi", "marks": [78, 85, 92]},
{"name": "Kiran", "marks": [45, 60, 38]},
{"name": "John", "marks": [90, 88, 95]},
{"name": "Anil", "marks": [55, 49, 70]},
]
# 1. Average for each student, rounded to 1 decimal place
averages = [round(sum(s["marks"]) / len(s["marks"]), 1) for s in students]
print(averages) # [85.0, 47.7, 91.0, 58.0]
# 2. Names of students who passed EVERY subject (40 or more)
passed_all = [s["name"] for s in students if all(m >= 40 for m in s["marks"])]
print(passed_all) # ['Ravi', 'John', 'Anil'] - Kiran has a 38
# 3. A grade label from each average. Two choices chain: A, else (B, else C).
grades = ["A" if avg >= 85 else "B" if avg >= 60 else "C" for avg in averages]
print(grades) # ['A', 'C', 'A', 'C']
# 4. Every mark from every student, in one flat list
all_marks = [m for s in students for m in s["marks"]]
print(all_marks) # [78, 85, 92, 45, 60, 38, 90, 88, 95, 55, 49, 70]
# 5. "Name: grade" lines, built with zip
print([f"{s['name']}: {g}" for s, g in zip(students, grades)])
# ['Ravi: A', 'Kiran: C', 'John: A', 'Anil: C']Key points
- A list comprehension is the empty-list-and-append loop in one expression.
- Read it from the for: "n * n, for each n in numbers".
- if at the END filters (no else); if/else at the FRONT chooses a value (else required).
- It always builds a NEW list; the original is not changed.
- It works on anything iterable: strings, range(), split(), enumerate(), zip(), dict.items().
- Nested for clauses go in loop order - outer first.
- Build grids with [[0] * n for _ in range(m)]; [[0] * n] * m shares one row.
- A comprehension’s variable does not leak; a for loop’s does.
- For actions use a loop; for totals and yes/no, pass the expression to sum(), any() or all().
- Choose a comprehension because it is clearer, not because it is a little faster.
Quick check before you move on
Interview questions
What is a list comprehension?
An expression that builds a new list from an iterable: [expression for item in iterable if condition]. It replaces the create-empty-list, loop, append pattern, and can transform and filter in one step.
Are list comprehensions faster than for loops?
Usually a little - the append happens inside the interpreter rather than through a method call each time; in our measurement it took about 91% of the loop’s time. The real reason to use one is readability; for large data where you only need to iterate once, a generator expression avoids building the list at all.
Does the loop variable of a comprehension leak into the surrounding scope?
Not in Python 3 - a comprehension has its own scope, so its variable disappears afterwards and cannot overwrite an outer name. In Python 2 it did leak; a regular for loop still does.
How do you flatten a list of lists?
[x for sub in nested for x in sub] - the for clauses in the same order as nested loops. For deeper or irregular nesting you need recursion or itertools.chain.from_iterable for one level.
When would you not use a list comprehension?
For side effects, for logic that needs statements such as break or try/except, when the result is only consumed once by sum(), any(), all() or a loop (use a generator expression), and whenever the one-liner is harder to read than the loop.
Quiz
- 1.
Rewrite as a comprehension: result = [], then for w in words: result.append(w.lower()).
- 2.
Why does [s for s in scores if s > 50 else 0] fail?
- 3.
Why does [[0] * 3] * 3 behave badly, and what is the fix?
- 4.
When is a plain for loop better than a comprehension?
- 5.
What is the difference between sum([n for n in nums]) and sum(n for n in nums)?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...