Python List Comprehensions — Map, Filter, and Nest
A lot of list code does one of three jobs: turn each item into a new item, keep only some items, or walk two lists at once. A comprehension writes each of those jobs as one line that reads in the order it runs: the source, the loop, the filter, and the value to keep. This guide builds the plain form first, then adds a filter, a choice inside the value, a second loop, and the dict and set forms, with a small working program for each step and the exact output it prints.
Written November 12, 2026 · Tested with Python 3.12.3 · 11 min read
- The main program: one line replaces a loop and an append
- A trailing if filters the items
- An if and else inside the expression picks a value
- Two for clauses walk pairs and flatten rows
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
A list comprehension builds a new list from an old sequence. It holds three parts in one pair of brackets: an expression for the value to keep, a for clause that walks the source, and an optional if clause that skips some items. Read it left to right in a different order than it is written. The for clause runs first, the if clause runs next for each item, and the expression runs last, once for each item that passes. Once that order is clear, the rest of this guide is variations: a harder filter, a choice inside the expression, a second for clause, and the same shape pointed at a dict or a set instead of a list.
The main program: one line replaces a loop and an append
The loop form of this job is four lines. The comprehension form is one line, and it produces the same list:
squares = []
for n in range(6):
squares.append(n * n)
print(squares)
comp = [n * n for n in range(6)]
print(comp)
print(comp == squares)
words = ["ana", "bo"]
print([w.upper() for w in words])
print([len(w) for w in words])
The exact output:
[0, 1, 4, 9, 16, 25]
[0, 1, 4, 9, 16, 25]
True
['ANA', 'BO']
[3, 2]
In [n * n for n in range(6)], the for clause feeds the values 0 through 5 to the expression n * n, and the results collect in order. The comparison on the third line returns True, so the short form is not a different tool. It is the loop with the bookkeeping removed. The last two lines show that the expression can be any call or operation on the loop variable. Here it is a method call that uppercases each word, and then a call that returns the length of each word. The source does not have to be a range. Any sequence or iterable works, and the result is always a new list. The source list itself stays as it was.
A trailing if filters the items
Add an if clause after the for clause, and only the items that pass reach the expression:
nums = list(range(10))
print([n for n in nums if n % 2 == 0])
print([n * n for n in nums if n % 2 == 1])
names = ["ana", "bo", "cy", "dana"]
print([name for name in names if len(name) > 2])
print([name for name in names if name.startswith("a")])
The exact output:
[0, 2, 4, 6, 8]
[1, 9, 25, 49, 81]
['ana', 'dana']
['ana']
The filter runs before the expression. In the second line, the odd numbers reach the squaring step, and the even numbers never do, so the result holds five squares rather than ten values with gaps. A filter can test the item in any way a plain if statement can. The third line keeps the names longer than two letters, and the fourth keeps the names that start with a. Nothing fills the spots the dropped items would have held. A filtered comprehension returns a shorter list, and its length tells you how many items passed.
An if and else inside the expression picks a value
A filter drops items. A conditional expression keeps every item and picks which value to store for it. The two forms look close and do different work:
print([n if n >= 0 else -n for n in [-2, -1, 0, 3]])
print(["even" if n % 2 == 0 else "odd" for n in range(5)])
print([n * 2 if n > 2 else n for n in range(5)])
The exact output:
[2, 1, 0, 3]
['even', 'odd', 'even', 'odd', 'even']
[0, 1, 2, 6, 8]
Place is the tell. An if with an else sits before the for clause, as part of the expression, because it needs both branches to produce a value for every item. A filter if sits after the for clause and has no else, because an item that fails it is simply left out. The first line turns each negative number into its positive form and keeps the rest as they are, so four numbers go in and four come out. The second line stores a word instead of a number. The third line doubles only the values above 2 and stores the others unchanged. If a line has both forms, read the trailing if first for which items survive, and the leading choice second for what each survivor becomes.
Two for clauses walk pairs and flatten rows
A comprehension can hold more than one for clause. The clauses nest in the order they are written, so the first clause is the outer loop and the next one is the inner loop:
pairs = [(x, y) for x in [1, 2] for y in ["a", "b"]]
print(pairs)
matrix = [[1, 2, 3], [4, 5, 6]]
print([n for row in matrix for n in row])
print([[row[i] for row in matrix] for i in range(3)])
The exact output:
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
[1, 2, 3, 4, 5, 6]
[[1, 4], [2, 5], [3, 6]]
In the pairs line, x holds at 1 while y runs through both letters, and then x moves to 2 and y runs again. That order matches two nested loops written with the x loop outside. The second print flattens a list of rows into one list. The outer clause picks a row, and the inner clause walks that row, so the numbers come out in reading order. The third print puts a comprehension inside a comprehension. The inner one collects one column, the item at index i from each row, and the outer one runs it for each column index. The result is the matrix turned on its side, with the rows and columns swapped. Nested forms get hard to read past two clauses. When a third clause or a long expression appears, a plain loop is usually the clearer tool for the same job.
The same shape builds a dict or a set
Change the brackets and the expression, and the same pattern builds a dict or a set. A dict comprehension stores a key and a value pair, split by a colon. A set comprehension stores single values and drops duplicates:
print({n: n * n for n in range(4)})
scores = {"ana": 3, "bo": 5}
print({name: score * 2 for name, score in scores.items()})
print({score: name for name, score in scores.items()})
lengths = {len(w) for w in ["ana", "bo", "cy", "dana"]}
print(sorted(lengths))
print(len(lengths))
print(sorted({w[0] for w in ["ana", "bo", "cy", "dana"]}))
The exact output:
{0: 0, 1: 1, 2: 4, 3: 9}
{'ana': 6, 'bo': 10}
{3: 'ana', 5: 'bo'}
[2, 3, 4]
3
['a', 'b', 'c', 'd']
The second line walks a dict with items, which hands the comprehension a key and a value at each step, and doubles each value while the keys stay put. The third line swaps the two, so the old values become the new keys. That swap has a trap worth knowing. If two names held the same score, the later one would overwrite the earlier one, because a dict holds one value per key. The set lines collect word lengths. Four words go in and three lengths come out, because two words share the length 2, and a set holds each value once. The sorted call in the prints gives the set a stable order to read. A set itself stores no order you should count on, so code that needs a fixed order should sort the result or keep a list instead.
enumerate, zip, and a generator inside a call
Three tools pair well with comprehensions. The enumerate function feeds an index beside each item, zip feeds one item from each of two sequences in step, and a call such as join can take a comprehension with the brackets left off:
names = ["ana", "bo", "cy"]
print([f"{i}:{name}" for i, name in enumerate(names, start=1)])
keys = ["a", "b"]
values = [1, 2]
print([(k, v) for k, v in zip(keys, values)])
print(" ".join(w.upper() for w in "ana bo".split()))
print([c for c in "abc" if c != "b"])
The exact output:
['1:ana', '2:bo', '3:cy']
[('a', 1), ('b', 2)]
ANA BO
['a', 'c']
The enumerate line starts its count at 1 rather than 0, and the f-string joins the count and the name into one stored string. The zip line stops when the shorter sequence runs out, so two keys and two values make two pairs. The join line holds a generator expression, which is a comprehension without brackets and without a list. It produces each uppercased word as join asks for it, and no list sits in between. The last line shows that a string is a sequence too. It walks the three letters and keeps the ones that are not b. Comprehensions work on any iterable, not only on lists, even though the result of the bracketed form is always a list.
The variable stays inside, and a generator runs once
Two facts about scope and reuse save debugging time. A comprehension has its own scope for its loop variable, and a generator expression produces its values once, on demand:
n = 99
vals = [n for n in range(3)]
print(vals)
print(n)
total = sum(n * n for n in range(5))
print(total)
gen = (n for n in range(3))
print(next(gen))
print(list(gen))
try:
print(len(gen))
except TypeError as e:
print(type(e).__name__)
print(e)
The exact output:
[0, 1, 2]
99
30
0
[1, 2]
TypeError
object of type 'generator' has no len()
The outer n is still 99 after the comprehension runs, because the n inside the brackets belongs to the comprehension alone. That differs from a plain for loop, whose variable keeps its last value after the loop ends. The sum line reads squares from a generator and adds them as they arrive, which suits a total that needs no list afterward. The gen lines show the cost of that form. The next call takes the first value, the list call takes the two that remain, and after that the generator is spent. It has no length, as the error shows, and a second pass over it would find nothing left. Pick the bracketed form when the code needs the values more than once, or needs a count or an index. Pick the generator form when one pass is enough and the source is long.
Which form for which job
| Job | Form | Why |
|---|---|---|
| Turn each item into a new item | Expression with one for clause | Each source item maps to one stored value |
| Keep only some items | Trailing if with no else | Items that fail the test are left out |
| Pick a value for every item | If and else before the for clause | Every item is stored, with a choice of value |
| Pair every item of one list with every item of another | Two for clauses | The clauses nest in written order |
| Flatten a list of rows | for row, then for item in row | Rows open one at a time in reading order |
| Build a dict from pairs | Braces with a key and value expression | One pair is stored per step |
| Collect distinct values | Set comprehension in braces | Duplicates drop as they arrive |
| Feed one pass into sum or join | Generator expression, no brackets | Values arrive on demand and no list is built |
| Store values for reuse, a count, or an index | List comprehension in brackets | A generator is spent after one pass |
Checklist
- Before reading a comprehension aloud, name the for clause first, then the filter, then the expression, in the order they run.
- Before adding an if, decide whether failing items should drop out or store a different value, and place the if on the matching side of the for clause.
- Before swapping keys and values in a dict comprehension, check for repeated values, which would overwrite each other as keys.
- Before printing or comparing a set result, sort it if the order matters to the reader or the test.
- Before using a generator expression, check that the code reads it once, because a second pass finds it spent.
- Before nesting a third for clause, try the plain loop form, which usually reads better at that size.
Related guides on this site
- Python Loops and Conditionals — for, while, if, range, and enumerate — the loop and if forms this guide compresses into one line.
- Python Lists, Dicts, and Sets — the three containers a comprehension builds, and how each one stores its values.
- Python Generators and Iterators — yield, next, and Lazy Sequences — the generator form in full, including what a spent iterator does on a second pass.
- Python Strings — Slicing, Methods, and f-Strings — the string methods and f-strings the examples use as expressions.
Sources
- Python Tutorial, Data Structures — the tutorial section on list comprehensions, nested list comprehensions, and the dict and set comprehension forms this guide follows.
- Python Language Reference, Expressions — the reference for comprehensions, generator expressions, and conditional expressions, including how the clauses nest and evaluate.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.