List Comprehension in Python
In this lesson: Write one-line loops with list comprehension in Python — filters, if-else, nested — compared with normal loops.
What is a comprehension?
A comprehension builds a new list, set or dictionary from existing data in one readable line. It replaces the common pattern “create an empty list → loop → append”.
prices = [120, 450, 80, 999]
# normal loop
with_gst = []
for p in prices:
with_gst.append(round(p * 1.18))
print(with_gst)
# list comprehension – same result
with_gst = [round(p * 1.18) for p in prices]
print(with_gst)Read it like English: [ expression for item in iterable if condition ] → “make expression for every item in iterable that passes condition”.
Filtering with if
marks = {"Asha": 91, "Ravi": 58, "Neha": 76, "Kabir": 34, "Isha": 88}
passed = [name for name, m in marks.items() if m >= 40]
toppers = [name for name, m in marks.items() if m >= 85]
print("Passed :", passed)
print("Toppers:", toppers)if-else inside the expression
To choose between two values (not to filter), put if … else … before for.
marks = [91, 58, 76, 34, 88] result = ["Pass" if m >= 40 else "Fail" for m in marks] grades = ["A" if m >= 85 else "B" if m >= 60 else "C" if m >= 40 else "F" for m in marks] print(result) print(grades)
| Position | Purpose | Example |
|---|---|---|
if after for | Keep only some items (filter) | [m for m in marks if m >= 40] |
if … else before for | Transform every item into one of two values | ["P" if m >= 40 else "F" for m in marks] |
Dictionary comprehension
items = ["kaju katli", "ghewar", "rasmalai"]
price = [900, 650, 700]
menu = {name.title(): p for name, p in zip(items, price)}
print(menu)
discounted = {k: round(v * 0.9) for k, v in menu.items() if v > 680}
print(discounted)
# swap keys and values
by_price = {v: k for k, v in menu.items()}
print(by_price[650])Set comprehension
emails = ["riya@gmail.com", "AMAN@yahoo.com", "neha@gmail.com", "aman@yahoo.com"]
domains = {e.split("@")[1].lower() for e in emails}
unique_users = {e.lower() for e in emails}
print(sorted(domains))
print(len(emails), "emails,", len(unique_users), "unique")Nested loops and flattening
sections = [["Asha", "Ravi"], ["Neha"], ["Kabir", "Isha", "Om"]]
# loops are written in the same order as normal nested for-loops
all_students = [s for section in sections for s in section]
print(all_students)
table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
for row in table:
print(row)If a comprehension needs more than two for parts or a long condition, write a normal loop. Clear code is better than clever code.
Real example: clean a messy student list
raw = [" asha sharma ", "RAVI kumar", "", "neha verma", " ", "Kabir Singh"]
clean = [" ".join(name.split()).title() for name in raw if name.strip()]
initials = {name: "".join(part[0] for part in name.split()) for name in clean}
print(clean)
print(initials)Is a comprehension faster?
import timeit
loop_code = """
result = []
for n in range(10000):
result.append(n * 2)
"""
comp_code = "result = [n * 2 for n in range(10000)]"
t_loop = timeit.timeit(loop_code, number=300)
t_comp = timeit.timeit(comp_code, number=300)
print("comprehension faster:", t_comp < t_loop)Usually yes, by about 20–40%, because the append happens inside optimised C code. But choose comprehensions mainly for readability; for side effects such as printing or saving, use a normal loop.
Common mistakes
| Mistake | Fix |
|---|---|
[x for x in data if x > 0 else 0] → SyntaxError | Move if-else before for: [x if x > 0 else 0 for x in data] |
Using a comprehension only to print: [print(x) for x in data] | Use a normal for loop |
| Very long nested comprehension | Split into a loop or helper function |
Expecting (x for x in data) to be a tuple | It is a generator; use tuple(...) |
Practice tasks
- From a list of numbers make a list of their cubes, keeping only odd numbers.
- From
{"pen": 10, "book": 250, "bag": 799}make a new dictionary with 18% GST added. - Make a set of all vowels that appear in a sentence.
- Flatten
[[1, 2], [3], [4, 5, 6]]and keep only even numbers.
Summary
[expr for x in data if cond]builds a list;{k: v for …}a dictionary;{expr for …}a set.ifafterforfilters;if/elsebeforeforchooses a value.- Multiple
forparts follow normal nested-loop order. - Prefer readability: switch to a loop when it gets complicated or has side effects.
