You have a list of prices in rupees and need the same prices with 18% GST added. With a loop, that's four lines: make an empty list, loop, calculate, append. A Python list comprehension does it in one line that reads almost like English: "price times 1.18, for each price in prices".
Comprehensions are everywhere in real Python code, in data science notebooks, interview answers and libraries. Python has them for lists, dictionaries and sets. This lesson shows how to read and write each kind, how to add conditions, and when a plain loop is the better choice.
What you need first: Python for and while loops, Python lists and Python dictionaries.
Key terms
- Comprehension: a short way to build a new list, dictionary or set from an existing collection, in one expression.
- Expression: the part that says what each new item should be, like
price * 1.18. - Iterable: anything you can loop over: a list, string, range, dictionary, file and more.
- Filter: an
ifat the end that keeps only some items. - Generator expression: a comprehension in round brackets that makes items one at a time instead of building a whole list.
How a list comprehension works
Here's the loop version and the comprehension version side by side:
prices = [100, 250, 499]
with_gst = []
for price in prices:
with_gst.append(round(price * 1.18, 2))
print(with_gst)
with_gst = [round(price * 1.18, 2) for price in prices]
print(with_gst)
[118.0, 295.0, 588.82]
[118.0, 295.0, 588.82]
The pattern is always:
[ expression for item in iterable ]
what to make where it comes from
Read it from the for: "for each price in prices, make round(price * 1.18, 2)". The square brackets mean the result is a list.
More examples:
names = ["ahana", "rohan", "meera"]
print([name.title() for name in names])
print([len(name) for name in names])
print([n * n for n in range(1, 6)])
['Ahana', 'Rohan', 'Meera']
[5, 5, 5]
[1, 4, 9, 16, 25]
Filtering with if
Add if at the end to keep only the items that pass a test:
marks = [35, 82, 47, 91, 28, 66]
passed = [m for m in marks if m >= 40]
print(passed)
[82, 47, 91, 66]
Read it as "m, for each m in marks, if m is at least 40".
if-else inside a comprehension
To change every item based on a condition, rather than drop some, put an if ... else expression at the front:
marks = [35, 82, 47, 91, 28, 66]
results = ["Pass" if m >= 40 else "Fail" for m in marks]
print(results)
['Fail', 'Pass', 'Pass', 'Pass', 'Fail', 'Pass']
This is the part that confuses people, so here's the rule:
| You want to | Where the condition goes | Example |
|---|---|---|
| Keep only some items | At the end, if only | [m for m in marks if m >= 40] |
| Transform every item two ways | At the front, if and else | ["Pass" if m >= 40 else "Fail" for m in marks] |
Putting else at the end is a SyntaxError:
marks = [35, 82]
bad = [m for m in marks if m >= 40 else 0]
SyntaxError: invalid syntax
Dictionary comprehensions
Use curly brackets with key: value:
students = ["Ahana", "Rohan", "Meera"]
name_lengths = {name: len(name) for name in students}
print(name_lengths)
prices = {"tea": 20, "coffee": 40, "samosa": 15}
discounted = {item: price * 0.9 for item, price in prices.items()}
print(discounted)
cheap = {item: price for item, price in prices.items() if price < 30}
print(cheap)
{'Ahana': 5, 'Rohan': 5, 'Meera': 5}
{'tea': 18.0, 'coffee': 36.0, 'samosa': 13.5}
{'tea': 20, 'samosa': 15}
Two handy patterns: building a dictionary from two lists with zip, and swapping keys and values.
names = ["Ahana", "Rohan", "Meera"]
scores = [88, 72, 95]
report = {n: s for n, s in zip(names, scores)}
print(report)
codes = {"MH": "Maharashtra", "KA": "Karnataka"}
reverse = {state: code for code, state in codes.items()}
print(reverse)
{'Ahana': 88, 'Rohan': 72, 'Meera': 95}
{'Maharashtra': 'MH', 'Karnataka': 'KA'}
When swapping, if two keys share a value, only the last one survives, because keys must be unique.
Set comprehensions
Curly brackets without a colon make a set, so duplicates disappear:
emails = ["a@gmail.com", "b@yahoo.com", "c@gmail.com"]
domains = {e.split("@")[1] for e in emails}
print(sorted(domains))
['gmail.com', 'yahoo.com']
See Python sets for more.
Generator expressions
Round brackets don't make a "tuple comprehension". They make a generator expression, which hands out items one at a time instead of storing them all. Pass one straight into sum, max, any or all:
marks = [35, 82, 47, 91, 28, 66]
print(sum(m for m in marks if m >= 40))
print(any(m < 30 for m in marks))
print(all(m > 20 for m in marks))
286
True
True
With a million numbers, sum(n * n for n in range(1_000_000)) never builds a million-item list, so it uses almost no memory. Generators get their own lesson in the advanced module.
Nested comprehensions
A comprehension can have two for parts. They run in the same order as nested loops written out:
pairs = [(size, colour) for size in ["S", "M"] for colour in ["red", "blue"]]
print(pairs)
[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]
Flattening a list of lists is a common use:
rows = [[1, 2, 3], [4, 5], [6]]
flat = [n for row in rows for n in row]
print(flat)
[1, 2, 3, 4, 5, 6]
To remember the order, write the loops out normally, then copy the for lines left to right in the same order:
for row in rows: -> for row in rows
for n in row: -> for n in row
flat.append(n) -> n (moves to the front)
A comprehension inside another builds a grid, such as a 3 × 3 multiplication table:
table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
print(table)
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
When not to use a comprehension
Comprehensions are for building a collection. Use a normal loop when:
- The logic needs more than one condition or step. Three
ifs and twofors in one line is hard to read and harder to debug. - You only want side effects, like printing.
[print(x) for x in items]works but builds a useless list ofNones. Write aforloop. - You need to handle errors with
try/exceptfor each item.
A good test: if you can't read your comprehension aloud in one breath, turn it into a loop.
Where comprehensions are used
- Data cleaning:
[s.strip().lower() for s in raw_names]. - Feature engineering in ML: building lists of features or labels from raw records.
- Reading files:
[line.strip() for line in f if line.strip()]gives every non-blank line. - Interviews: interviewers expect fluent Python, and comprehensions are one of the first things they look for.
Practice
- Make a list of the cubes of the numbers 1 to 6.
Show the answer
print([n ** 3 for n in range(1, 7)])
[1, 8, 27, 64, 125, 216]
- From
words = ["Python", "is", "a", "great", "language"], keep only the words with more than 2 letters, in upper case.
Show the answer
words = ["Python", "is", "a", "great", "language"]
print([w.upper() for w in words if len(w) > 2])
['PYTHON', 'GREAT', 'LANGUAGE']
- Replace every negative number in
[4, -2, 7, -9, 0]with 0, keeping the others.
Show the answer
Every item stays, but some change, so the if ... else goes at the front:
nums = [4, -2, 7, -9, 0]
print([n if n > 0 else 0 for n in nums])
[4, 0, 7, 0, 0]
- Turn
"tea=20,coffee=40,samosa=15"into the dictionary{'tea': 20, 'coffee': 40, 'samosa': 15}with numbers as values.
Show the answer
Split on commas, then split each part on =:
text = "tea=20,coffee=40,samosa=15"
menu = {part.split("=")[0]: int(part.split("=")[1]) for part in text.split(",")}
print(menu)
{'tea': 20, 'coffee': 40, 'samosa': 15}
A neater version unpacks each pair: dict(part.split("=") for part in text.split(",")) gives string values, which you could then convert.
- Rewrite this loop as a comprehension.
result = []
for x in range(1, 4):
for y in range(1, 4):
if x != y:
result.append((x, y))
print(result)
Show the answer
Copy the for and if lines in the same order, then move what is appended to the front:
result = [(x, y) for x in range(1, 4) for y in range(1, 4) if x != y]
print(result)
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
- Using a generator expression, count how many words in
"the cat sat on the mat"have exactly 3 letters.
Show the answer
True counts as 1 and False as 0, so summing the test counts the matches:
sentence = "the cat sat on the mat"
print(sum(len(w) == 3 for w in sentence.split()))
5
"the", "cat", "sat", "the" and "mat" have 3 letters; "on" has 2.
Interview questions
What is the difference between [x for x in items] and (x for x in items)?
Square brackets build a full list in memory straight away. Round brackets create a generator, which produces items one at a time only when asked, and can be looped over only once. Generators save memory for large data.
Where does the if go in a list comprehension?
A filter if with no else goes at the end and drops items. A conditional expression a if cond else b goes at the front and transforms every item.
Are list comprehensions faster than for loops?
Usually a little faster than a loop that calls append, because the work happens inside Python's interpreter without a method call each time. The main reason to use them is readability, though, not speed.
Key takeaways
[expression for item in iterable]builds a list; read it starting fromfor.- A filter
ifgoes at the end; anif ... elsethat transforms every item goes at the front. {k: v for ...}builds a dictionary and{x for ...}builds a set.- Round brackets make a generator expression, ideal inside
sum,any,allandmax. - Nested
forparts run in the same order as written-out loops; switch to a normal loop when it gets hard to read.
Frequently asked questions
Is there a tuple comprehension in Python?
No. (x for x in items) is a generator expression. To get a tuple, wrap it: tuple(x for x in items).
Can I use a function call inside a comprehension?
Yes, the expression and the condition can both call functions, such as [clean(s) for s in names if is_valid(s)]. Moving complex logic into a named function keeps the comprehension readable.
Do comprehension variables leak outside?
No, not in Python 3. The loop variable inside a comprehension is local to it, unlike a normal for loop, whose variable is still set after the loop ends.
What to learn next
- Work with lists of dictionaries in nested data and JSON in Python.
- Pair comprehensions with functions in lambda, map, filter and sorted.
- Revise the basics in Python lists.