Skip to content
IT Vizag
← Advanced Python Features

Comprehensions

Lesson 1 of 10 · 2 min read

List, dict and set comprehensions: one clear line instead of four.

🎬 Video version coming soon — read it now

A comprehension builds a list, dictionary or set in one readable line. Experienced Python developers use them constantly, so you need to read and write them fluently.

List comprehensions

# Loop version
squares = []
for n in range(1, 6):
    squares.append(n * n)

# Comprehension
squares = [n * n for n in range(1, 6)]     # [1, 4, 9, 16, 25]

Read it as: "*n n, for each n in** range(1, 6)".

With a filter

marks = [78, 32, 65, 18, 88]
passed = [m for m in marks if m >= 35]           # [78, 65, 88]
names = [s.strip().title() for s in [" anil ", "BHAVANA"]]

If/else inside (a different position!)

results = ["Pass" if m >= 35 else "Fail" for m in marks]

A filter if goes at the end and drops items. A choice if/else goes at the front and keeps every item.

Dict and set comprehensions

prices = {"idli": 40, "dosa": 60, "vada": 30}
with_gst = {item: round(p * 1.05, 2) for item, p in prices.items()}

words = "the sea the sand the sun".split()
unique_lengths = {len(w) for w in words}       # {3, 4}

index = {name: i for i, name in enumerate(["Anil", "Bhavana"])}

Nested loops

pairs = [(r, c) for r in range(3) for c in range(3) if r != c]
flat = [x for row in [[1, 2], [3, 4]] for x in row]    # [1, 2, 3, 4]

The for clauses read in the same order as nested loops would.

Generator expressions

Swap the square brackets for round ones and nothing is stored; values are produced one at a time:

total = sum(m * m for m in range(1_000_000))

This uses almost no memory. More on that in the generators lesson.

When NOT to use a comprehension

If it needs two conditions, nested comprehensions, or doesn't fit comfortably on one or two lines, use a normal loop. Comprehensions are for clarity; a clever one-liner nobody can read is worse than five plain lines.

Tip: Never use a comprehension just for side effects, like [print(x) for x in items]. Use a for loop when you're doing something rather than building a collection.

In one line

[expr for x in items if cond] builds lists in one clear line; use dict and set versions too, and a plain loop when it stops being readable.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend