A Python list comprehension builds a new list in one line: [expression for item in iterable]. That’s the whole idea. But the syntax stretches a lot further than squaring numbers, and it also has a few sharp edges that bite people who learned it from a cheat sheet.
Below are 12 patterns worth knowing, from the basic filter to the walrus operator. We ran every snippet on Python 3.12.4 and pasted the real output underneath each one. At the end there’s a section most tutorials leave out: when you shouldn’t use a comprehension at all.
Python list comprehension syntax in 30 seconds
Read a comprehension left to right as “give me this, for each item in that, if this condition holds.” The parts are the expression, one or more for clauses, and optional if clauses. The brackets decide what you get back: square brackets make a list, curly braces make a set or dict, and round brackets make a generator. The official Python tutorial describes them as a concise way to create lists, and that’s the best way to think about them: a shortcut for building something, not a general-purpose loop.

The basics: transform and filter
1. Replace a for loop that appends
This is the pattern comprehensions were made for. Any time you create an empty list and then append inside a loop, you can probably collapse it.
squares = []
for n in range(6):
squares.append(n * n)
squares = [n * n for n in range(6)]
print(squares)
# [0, 1, 4, 9, 16, 25]
Is it faster, or just shorter? Both, a little. Building a 1,000-item list 5,000 times took 1.90 seconds with the append loop and 1.04 seconds with the comprehension on our Windows test machine. Your numbers will differ, and for most scripts the difference won’t matter. Python 3.12 also inlines comprehensions instead of creating a hidden function each time, which the 3.12 release notes say makes them up to twice as fast as before.
2. Filter with if
Put an if at the end to keep only the items you want.
scores = [72, 45, 90, 38, 66]
passed = [s for s in scores if s >= 50]
print(passed)
# [72, 90, 66]
3. List comprehension with if else
This one confuses almost everybody at first. A filter if goes at the end. An if/else that chooses a value goes at the front, because it’s part of the expression, not a filter.
labels = ["pass" if s >= 50 else "fail" for s in scores]
print(labels)
# ['pass', 'fail', 'pass', 'fail', 'pass']
Put else at the end and you’ll get a SyntaxError. Rule of thumb: if every item makes it into the result, the condition belongs at the front.
4. Clean up strings in one pass
You can chain method calls in the expression. It’s the quickest way to tidy user input or a column from a CSV.
raw = [" Alice ", "BOB", " carol"]
names = [name.strip().title() for name in raw]
print(names)
# ['Alice', 'Bob', 'Carol']
Nested list comprehension patterns
5. Flatten a list of lists
Two for clauses run in the same order as nested loops would: outer first, inner second. People often write them backwards. If it helps, write the normal nested loop first and then copy the for lines across in the same order.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in grid for x in row]
print(flat)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
6. Every combination of two lists
Same double for, but the expression uses both variables. Handy for test cases or building grid coordinates.
pairs = [(x, y) for x in "ab" for y in range(3)]
print(pairs)
# [('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2)]
For anything bigger than two short lists, itertools.product reads better.
7. Build a 2D grid without the shared-row bug
Here’s a bug that catches people for years. Multiplying a list of lists copies the reference, so every row is the same object. A comprehension creates a fresh row each time.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad)
# [[1, 0, 0], [1, 0, 0]] both rows changed
good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good)
# [[1, 0, 0], [0, 0, 0]]
8. Transpose rows and columns
A comprehension inside a comprehension builds a nested result. This flips rows into columns:
grid = [[1, 2, 3], [4, 5, 6]]
cols = [[row[i] for row in grid] for i in range(3)]
print(cols)
# [[1, 4], [2, 5], [3, 6]]
print([list(c) for c in zip(*grid)])
# [[1, 4], [2, 5], [3, 6]]
Both give the same answer. We’d use the zip(*grid) version in real code. It doesn’t need the column count, and it’s the idiom other Python developers will recognise.

Beyond lists: dict, set and generator comprehensions
9. Dict and set comprehensions
Swap the square brackets for curly braces. With a key: value pair you get a dict; with a single expression you get a set, which drops duplicates for free.
words = ["apple", "kiwi", "banana"]
lengths = {w: len(w) for w in words}
print(lengths)
# {'apple': 5, 'kiwi': 4, 'banana': 6}
initials = {w[0] for w in words + ["avocado"]}
print(sorted(initials))
# ['a', 'b', 'k']
10. Generator expressions for sum, any and all
If you only need to loop over the result once, drop the brackets. A generator expression produces values one at a time instead of building the whole list in memory.
total = sum(n * n for n in range(1_000_000))
print(total)
# 333332833333500000
emails = ["a@x.com", "bad-address", "c@y.org"]
print(any("@" not in e for e in emails))
# True
import sys
print(sys.getsizeof([n for n in range(1_000_000)]))
# 8448728
print(sys.getsizeof(n for n in range(1_000_000)))
# 192
That’s about 8.4 MB for the list object against 192 bytes for the generator on our run. any() and all() also stop early once they know the answer, which a list can’t do because it’s already been built.
Newer tricks: walrus, zip and enumerate
11. Compute once with the walrus operator
Sometimes you need a computed value both to filter and to keep. Without := you’d calculate it twice. Python 3.8 added the walrus operator, and it works inside the if of a comprehension.
def to_int(s):
try:
return int(s)
except ValueError:
return None
raw = ["10", "-3", "4.5", "x"]
print([n for s in raw if (n := to_int(s)) is not None])
# [10, -3]
print([int(s) for s in raw if s.isdigit()])
# [10] isdigit() silently drops "-3"
Look at that second line. The common shortcut s.isdigit() rejects negative numbers, so “-3” just vanishes with no error. The walrus version keeps it. One quirk: a walrus variable leaks out of the comprehension. After the line runs, n still exists in the outer scope, while the normal loop variable s doesn’t.
12. Pair lists with zip and number them with enumerate
Comprehensions combine nicely with zip() and enumerate(). Since Python 3.10, zip(..., strict=True) raises an error when lists have different lengths instead of quietly cutting the longer one short.
names = ["Ana", "Ben", "Cy"]
ages = [31, 25, 40]
print([f"{n} ({a})" for n, a in zip(names, ages, strict=True)])
# ['Ana (31)', 'Ben (25)', 'Cy (40)']
print([f"{i}. {name}" for i, name in enumerate(names, start=1)])
# ['1. Ana', '2. Ben', '3. Cy']
[a + b for a, b in zip([1, 2, 3], [10, 20], strict=True)]
# ValueError: zip() argument 2 is shorter than argument 1
The catch: plenty of tutorials still claim that comprehension variables leak into the surrounding code. That was true in Python 2. In Python 3, the loop variable stays inside, and the 3.12 docs confirm inlining didn’t change that. We checked: with x = "outer" before [x for x in range(3)], x is still "outer" afterwards. The exception is the walrus operator from pattern 11, which does leak on purpose.
When not to use a list comprehension
Comprehensions are for building a value. When they start doing other jobs, a plain loop is clearer. Here’s where we’d stop:
- Side effects.
[print(x) for x in items]works, but it builds a throwaway list ofNonevalues. We ran[out.append(n) for n in range(3)]and got[None, None, None]back. Use a for loop. - More than two
forclauses, or an if/else plus a filter. If you need to read it twice to follow it, so will the next person. - Error handling. You can’t put
try/exceptinside a comprehension. Move that logic into a small function, as in pattern 11, or use a loop. - Huge or endless data. A list comprehension holds everything in memory. Use a generator expression or a loop that processes items as they arrive.
- When you need to stop early with
break. Comprehensions can’t break.next()with a generator, or a loop, can.
A good test is the read-aloud one. If you can say the comprehension as a single sentence, keep it. If you need “and then” more than once, write the loop.
Which patterns to learn first
If you’re new to Python, learn patterns 1 to 4 this week. They cover most of what you’ll write day to day. Add the generator expression (10) and the grid fix (7) next, because both prevent real bugs. Leave the walrus and transpose tricks until you need them.
For more small features like these, read our 15 Python tricks for beginners, all tested on the same Python version. And if you ask an AI assistant to refactor loops into comprehensions, our AI prompts for coding include a review prompt that catches the side-effect mistake above.
Next: doing the same kind of thing in another language? See our JavaScript one-liners, where map and filter play the same role. Formatting the results nicely is the next step: Python f-string tricks you probably haven’t used.
FAQ
Are list comprehensions faster than for loops?
Usually a bit, for simple build-a-list jobs. In our run the comprehension took about 55% of the loop’s time. If the expression itself is slow, such as a network call, the difference disappears.
Where does else go in a list comprehension?
At the front, as part of the expression: [a if cond else b for x in items]. A filtering if with no else goes at the end.
Can a list comprehension have two for loops?
Yes. They run in the same order as nested loops written out normally: outer loop first. See patterns 5 and 6.
What’s the difference between a list comprehension and a generator expression?
Square brackets build the full list straight away. Round brackets give a generator that yields one value at a time, uses far less memory, and can only be looped over once.