Python List Comprehension: Syntax, Filtering, if-else
A Python list comprehension builds a new list in one line: [expression for item in items], with an optional if condition at the end to keep only some items. For example, [p for p in prices if p < 10] returns just the prices under 10.
On this page▾
- How does a list comprehension work?
- How do you filter a list comprehension with if?
- Where does if-else go in a list comprehension?
- Cleaning data in one pass
- Two for clauses: flattening a list of lists
- The same idea for dictionaries and sets
- No leftover loop variable
- When to use a regular loop instead
- Can you use a filter and if-else together?
- Does a comprehension change the original list?
- What to check before using this syntax
| Goal | Pattern | Example |
|---|---|---|
| Transform every item | [f(x) for x in items] |
[x*2 for x in [1, 2, 3]] gives [2, 4, 6] |
| Keep some items | [x for x in items if cond] |
[x for x in [-1, 2, 3] if x >= 0] gives [2, 3] |
| Pick one of two values | [a if cond else b for x in items] |
["pass" if s >= 65 else "retry" for s in scores] |
| Flatten a list of lists | [n for sub in lists for n in sub] |
[1, 2, 3, 4] from [[1, 2], [3, 4]] |
How does a list comprehension work?
A comprehension evaluates the expression for each item that passes its filters and collects those results in a new list. The input can be a list or another iterable, such as a string or a range.
Here is a loop that adds 8 percent tax to a list of prices:
prices = [12.0, 7.5, 30.0, 4.25]
with_tax = []
for p in prices:
with_tax.append(round(p * 1.08, 2))
print(with_tax)
with_tax = [round(p * 1.08, 2) for p in prices]
print(with_tax)
[12.96, 8.1, 32.4, 4.59]
[12.96, 8.1, 32.4, 4.59]
Both produce the same list. Read the comprehension from the middle out:
for p in prices: go through each price.round(p * 1.08, 2): work out this value for each one.[ ... ]: collect the results in a new list.
The brackets contain an expression followed by a for clause, then zero or more for or if clauses.
How do you filter a list comprehension with if?
Put an if at the end to keep only some items:
prices = [12.0, 7.5, 30.0, 4.25]
cheap = [p for p in prices if p < 10]
print(cheap)
[7.5, 4.25]
Here the expression is just p, so each kept price goes into the new list unchanged.
Where does if-else go in a list comprehension?
Sometimes you want to keep every item but transform it one of two ways. That uses a conditional expression: x if condition else y. It goes at the front, in the expression position:
scores = [91, 58, 77, 64, 100]
labels = ["pass" if s >= 65 else "retry" for s in scores]
print(labels)
['pass', 'retry', 'pass', 'retry', 'pass']
The two forms are easy to mix up. A filter if at the end decides which items appear. A conditional if-else at the front decides what value each item becomes. Putting else at the end is a syntax error:
labels = [s for s in scores if s >= 65 else 0]
SyntaxError: invalid syntax
The exact wording of the error can vary between Python versions.
Cleaning data in one pass
Comprehensions combine well with string methods. Here, empty entries are dropped and the rest are converted to uppercase:
codes = ["ab-104", "", "cd-221", "ef-309", ""]
clean = [c.upper() for c in codes if c]
print(clean)
['AB-104', 'CD-221', 'EF-309']
if c works because an empty string counts as false in Python.
The string methods used for cleaning, such as strip() and split(), are covered in Python strip(), split(), join(), replace() for Beginners.
Two for clauses: flattening a list of lists
Chain for clauses to handle nested lists. Their order is the same as in nested loops: the first for is the outer loop.
teams = [["mina", "leo"], ["sam"], ["ana", "raj", "kim"]]
people = [name for team in teams for name in team]
print(people)
['mina', 'leo', 'sam', 'ana', 'raj', 'kim']
Read it as "for each team, for each name in that team, keep the name."
The same idea for dictionaries and sets
Curly braces give you a dictionary or set comprehension:
names = ["mina", "leo", "sam"]
lengths = {n: len(n) for n in names}
print(lengths)
first_letters = {n[0] for n in ["mina", "mark", "leo"]}
print(sorted(first_letters))
{'mina': 4, 'leo': 3, 'sam': 3}
['l', 'm']
key: value before the for makes a dictionary. A single expression inside braces makes a set, so the duplicate "m" appears only once.
No leftover loop variable
A regular for loop creates or overwrites its loop variable, and that variable still exists after the loop ends. A comprehension keeps its variable to itself:
for x in [1, 2, 3]:
pass
print(x)
squares = [n * n for n in [1, 2, 3]]
print(squares)
print(n)
3
[1, 4, 9]
NameError: name 'n' is not defined
After the loop, x is still 3. After the comprehension, n does not exist. That means a comprehension cannot accidentally overwrite a variable you were using elsewhere.
When to use a regular loop instead
Comprehensions are for building a list. Use a normal loop when:
- the body needs several steps, or would need a comment to explain;
- you are doing something for its effect, like printing or saving files, rather than collecting results;
- the comprehension stops fitting comfortably on one line.
A good test: if you have to read it twice, write the loop.
Can you use a filter and if-else together?
Yes. The final filter decides which scores survive; the expression at the front labels only those scores. Adding enumerate(..., start=1) keeps the original position beside each label:
scores = [91, 58, 77, 64, 100]
results = [
(i, "pass" if s >= 65 else "retry")
for i, s in enumerate(scores, start=1)
if s >= 60
]
print(results)
[(1, 'pass'), (3, 'pass'), (4, 'retry'), (5, 'pass')]
The score 58 disappears, but 64 stays with a retry label. The index 2 is missing because numbering happened before filtering. Parentheses around (i, label) make each result a tuple; writing two comma-separated expressions without those parentheses is not valid comprehension syntax.
Does a comprehension change the original list?
It creates a new list rather than replacing the input. In the price example, prices still contains the original prices after with_tax is built. Assigning a comprehension back to the same name, such as prices = [p for p in prices if p < 10], instead makes that name refer to the new result.
What to check before using this syntax
These examples use ordinary Python 3 comprehension syntax. Check the brackets first, then read the for and filter clauses in loop order. An empty input or a filter that rejects every item produces [], not an error. If you need positions, choose whether to number the original input or the filtered result before placing enumerate().
Sources
About this guide
Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.
AboutEditorial standardsCorrectionsReport an error
Edit history
- Updated
- Updated
- Updated
- Updated
- Published