The translation
Nearly every comprehension started life as this shape:
result = []
for item in things:
result.append(f(item))
which becomes:
result = [f(item) for item in things]
Read it left to right: what to build, then where the items come from. The three moving parts of the loop — create the list, iterate, append — collapse into one line where the intent is the first thing you see.
The loop version is not wrong. It works, and for complex logic it is often clearer. But the pattern of starting with an empty list, looping, and appending one item per pass is so common that Python gives it a shorter spelling. The comprehension does exactly the same work. It builds the same list in the same order. The difference is that the intent appears on a single line, and you do not need to scan three lines to confirm the pattern.
One practical benefit is that comprehensions prevent a whole class of small bugs. With the loop version, you might forget to initialize the list, append to the wrong variable, or accidentally reuse a list from a previous block. The comprehension handles all three in one expression. There is no empty list to forget and no append call to misplace.
Comprehensions also accept a trailing if clause for filtering. You can build a list of only the items that pass a test, without writing an extra indentation level. When a comprehension grows past one line or needs nested logic, switch back to a loop. Readability is the whole point, and a three-line comprehension that wraps across four lines has lost that advantage. This page covers the basic translation from loop to comprehension, filtering with if, and the limits of when a comprehension still makes sense.
Filtering
An if at the end keeps only some items:
evens = [n for n in nums if n % 2 == 0]
That is the filter spot, and it takes no else. If you want to choose between two values rather than keep or drop, the if-based goes in the formula at the front instead:
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
Two different ifs, in two different places, doing two different jobs. Mixing them up is the most common comprehension error.
Nesting reads outer-first
[n for row in grid for n in row]
The clauses come in the same order as the nested loops would: for row outside, for n inside. It reads oddly because the formula sits before both. The order after the formula is just the loop order.
One level of nesting is defensible. Two, plus a filter, is a line that will cost you a minute each time you come back to it. And the loop version costs nothing. The second program on this page puts both side by side and prints the same answer from each.
Comprehension or generator
Swap the brackets for round ones and you get a gen formula:
total = sum(n * n for n in range(10_000))
The comprehension builds the whole list first. each element in memory. Then sums it. The gen makes one value at a time and never builds a list at all. When the result is consumed right away by sum, any, max or a for, the gen is the better default. The size difference is measurable: the page prints both.
A worked example, step by step
Take a list of records and pull out the names of everyone who passed:
rows = [{"name": "ana", "score": 91},
{"name": "bo", "score": 43},
{"name": "cy", "score": 68}]
passed = [r["name"] for r in rows if r["score"] >= 50]
Read it in the order it executes. This Isn't the order it's written: take each r from rows, keep it if the score clears 50, and collect r["name"]. The formula at the front is applied last, to what lives the filter.
Written as a loop that is four lines and one more variable to name.
The variable does not leak
squares = [n * n for n in range(5)]
print(n) # NameError
The loop variable belongs to the comprehension and is gone afterwards. That is a deliberate difference from a for statement, whose variable outlives the loop, and it's the reason a comprehension can't quietly overwrite an n you were using elsewhere.
Conditional expression versus filter, once more
These two look similar and do different jobs:
[n for n in nums if n > 0] # filter: some items are dropped
["pos" if n > 0 else "neg" for n in nums] # map: every item is kept
The first can return a shorter list. The second always returns one item per input. If you find yourself wanting if ... else at the end, you almost certainly want it at the front instead.
Building a dict or a set the same way
The syntax generalises:
{w: len(w) for w in words} # dict comprehension
{len(w) for w in words} # set comprehension
Braces with a colon give a dict. Braces without give a set. Both take the same trailing if, and both are worth reaching for when the loop version would be three lines of result[key] = value.
What a comprehension is really for
The value of a comprehension isn't that it's shorter. It's that it says "this is a change" in a way a loop can't. A loop that builds a list is three separate statements - create, iterate, append - and a reader has to hold all three to work out that nothing else is happening in between. A comprehension states the shape of the result on the first line, and there's nowhere for any of it else to hide.
That is also the test for whether you should use one. If the body does one thing to each item, a comprehension expresses it better. If it does a few things, updates a thing outside itself, or needs a try, the loop isn't just acceptable but correct, because those are just the things a comprehension can't hold and shouldn't be contorted into.
A note on nesting
A comprehension holding a second for is a nested loop, and it's subject to the same times of work given elsewhere on this site. Flattening a list of lists is a fair use. Checking each pair of items isn't - it's the same quadratic cost written more compactly, and compactness is the last thing that helps when a thing is slow.
What a comprehension cannot contain
The limits aren't any. They follow from a comprehension being an formula, and knowing them tells you just when to stop trying.
No statements. No set with =, no return, no raise, no pass. The walrus := is the one exception, added just because naming an mid value was the one statement people truly needed.
**No try.** If one item might raise, a comprehension can't handle it. The whole thing fails and you lose the items already processed. A loop with a try inside is the only way to skip the bad ones and keep the rest, and that is a common enough need that it alone decides the shape of a lot of data-cleaning code.
**No break or continue.** A filter can drop items. But Nothing can stop the iteration early. itertools.takewhile covers the break case, and the trailing if covers continue.
Nothing handy for side effects. A comprehension whose result is discarded — [print(x) for x in items]. Builds a list of None to throw away, and hides that iteration is the point. Write the loop.
Each of those is a signal rather than an obstacle. When you find yourself wanting one, the answer isn't a cleverer comprehension. It's that the job has outgrown the form.
Reading one somebody else wrote
Comprehensions are written left to right and ran in a different order, which is what makes an unseen one hard to parse. A solid method:
**Find the for clauses first.** Read them left to right. They're the loops, outermost first. Skip all before the first for while you do this.
**Then the trailing if.** It filters what the loops made, and it runs before the formula at the front.
Then the formula. It applies last, to each surviving item, and it's what the result holds.
Finally the brackets. Square gives a list, braces a set, braces with a colon a dict, round a gen that hasn't run yet.
So [f(x) for row in grid for x in row if x] reads as: for each row in grid, for each x in row, keep the truthy ones, and collect f(x). Four clauses, read in the order they execute. This Is right to left except for the formula that comes first on the page.
The value of having a method is that it also tells you when a comprehension is too much: if the method takes more than a few seconds, the loop version would have been read in one pass.
The cost, and where the loop wins
A comprehension is often a little faster than the equal loop, because the appending happens in the interpreter's own loop rather than through a method lookup on each pass. The difference is real and small, and it's almost never the deciding factor.
Where the difference does matter is memory. A list comprehension over a large input builds the whole result before any of it else happens. A gen formula doesn't. For a file with millions of lines, that is the difference between a program that runs and one that doesn't, and it costs one character to switch.
Where the loop truly wins is all the previous section listed, plus one more: debugging. You can put a print or a breakpoint inside a loop body. You can't put one inside a comprehension without changing it into a thing else. When a change is making the wrong answer and you don't know why, converting it to a loop for five minutes is often the fastest route to the cause.
The shape it replaces, and the one it does not
A comprehension replaces just one loop shape: build an empty collection, iterate, append a thing derived from each item. Recognising that shape is how you know a comprehension applies without having to try it.
The tell is that the accumulator is only ever appended to, and the thing appended depends only on the current item. Nothing reads the accumulator, no other variable is updated, and the loop body is a single formula.
The shapes it doesn't replace are worth naming, because they look similar.
Building up. A running total, a max so far, a count — any of it where the next value depends on what came before. Comprehensions have no access to what they've already made. This Is why sum, max and Counter exist as separate tools.
Grouping. Building a dict of lists needs to append to an entry that may already exist, which is a read of the accumulator. setdefault or defaultdict in a loop is the answer.
Two outputs. Splitting one input into two lists in a single pass. A comprehension makes one collection, so this is either two comprehensions over the same data or one loop. And the loop reads the input once.
Questions people ask about List Comprehensions
Is a comprehension faster than a loop? Slightly, for building a list. Not enough to choose one for that reason.
Can I use two filters? Yes, and chained filters mean and.
Why does my nested comprehension have the loops backwards? Because the clauses read outer-first, the same order as nested for statements. It's the guess most people get wrong.
Can I ref the previous item? Not right. Zip the list with a shifted copy of itself, or write the loop.
Does the loop variable leak? No, a comprehension has its own scope. A for statement doesn't.
Can I build a list of lists? Yes, with a comprehension in the formula slot: [[f(x) for x in row] for row in grid].
When should I definitely not use one? When the body needs a try, a break, an set, or exists for a side effect.
Can a comprehension be spread over a few lines? Yes, and it often should be — one clause per line, with the formula on the first, reads far better than a long single line.
Is there a limit to how many for clauses I can use? No limit in the language, and a hands-on one of about two before it stops being readable.
Why does a gen formula inside a function call need no extra brackets? Because it's the only arg. With more than one arg, the brackets are needed to say where it ends.
Should I name the result of a comprehension? Almost always. A comprehension passed straight into another call is compact and gives the reader nothing to hold on to. A name says what the collection is.
List Comprehensions: recap in one screen
- A comprehension states the shape of the result first. This Is what makes it clearer than a loop for a plain change.
- The
for clauses read outermost-first. The trailing filter runs before the formula at the front. - It's an formula, so no statements, no
try, no break — and those limits are the signal to write the loop. - Round brackets give a gen that builds nothing. This Is the right default inside
sum, any, max and join. - One
for, one filter: past that, the loop is easier to read, to change and to debug.