Course Progress69%
🍎 Python Practical Python Topic 69 / 100
⏳ 7 min read

Comprehension Tricks

Conditional, nested, and multi-type comprehensions — and the honest advice on when to stop using them.

"Comprehensions are Python's gift for writing clean, expressive one-liners. But like any power tool, they can hurt you if you use them wrong."

— ShurAI

Quick Recap: Basic Comprehensions

You’ve seen list comprehensions. Here’s a quick reminder of all four types before we go deeper:

python — four comprehension types
# List comprehension — [expression for item in iterable]
squares = [n**2 for n in range(5)]      # [0, 1, 4, 9, 16]

# Set comprehension — {expression for item in iterable}
unique  = {n % 3 for n in range(9)}     # {0, 1, 2}

# Dict comprehension — {k: v for item in iterable}
squared = {n: n**2 for n in range(4)}   # {0:0, 1:1, 2:4, 3:9}

# Generator expression — (expression for item in iterable)
total   = sum(n**2 for n in range(5))   # 30 — no list created

Conditional Filtering — the if Clause

Add if condition at the end to filter items:

python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Keep only even numbers
evens = [n for n in numbers if n % 2 == 0]
# [2, 4, 6, 8, 10]

# Keep only words longer than 3 chars
words = ["hi", "hello", "hey", "greetings", "ok"]
long_words = [w for w in words if len(w) > 3]
# ['hello', 'greetings']

if/else Inside the Expression

Put the if/else before for to transform values (not filter them):

python
numbers = [1, 2, 3, 4, 5]

# Replace even numbers with "even", odd with "odd"
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
# ['odd', 'even', 'odd', 'even', 'odd']

# Cap scores at 100
scores  = [85, 102, 78, 110, 95]
capped  = [100 if s > 100 else s for s in scores]
# [85, 100, 78, 100, 95]
Position of if changes the meaning:
[x if x > 0 else 0 for x in nums]
if/else before for → transforms every item (keeps same count)
[x for x in nums if x > 0]
if after for → filters items (may have fewer results)

Nested Comprehensions

You can nest loops — useful for flattening nested lists or building grids:

python
# Flatten a 2D list into 1D
matrix  = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat    = [n for row in matrix for n in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Build multiplication table as dict
table = {(i, j): i*j for i in range(1, 4) for j in range(1, 4)}
# {(1,1):1, (1,2):2, (1,3):3, (2,1):2, ...}

When to STOP Using Comprehensions

⚠️ If you can’t read it aloud clearly, rewrite it as a loop

Comprehensions are great for simple transformations and filters. But nesting more than two levels, adding complex logic, or squeezing multiple operations in — that’s when readability collapses. A plain for loop is always fine.

python — too clever = unreadable
# Bad: what does this even do at first glance?
result = [x**2 for x in [n for n in range(20) if n % 2 == 0] if x > 10]

# Good: same logic, clear steps
evens  = [n for n in range(20) if n % 2 == 0]
result = [x**2 for x in evens   if x > 10]

Real Example — Data Cleaning Pipeline

python
raw_data = [" Riya ", "ARJUN", "", "  sneha", "VIKRAM  ", " "]

# Step 1: strip whitespace
stripped = [name.strip() for name in raw_data]

# Step 2: remove empty strings
non_empty = [name for name in stripped if name]

# Step 3: title-case all names
clean = [name.title() for name in non_empty]

print(clean)
# ['Riya', 'Arjun', 'Sneha', 'Vikram']

"The goal of a comprehension is not to impress — it's to communicate. If the one-liner takes longer to read than the loop it replaces, write the loop."

— ShurAI

🧠 Quiz — Q1

What does [n for n in nums if n > 0] do?

🧠 Quiz — Q2

What is the difference between [x if x > 0 else 0 for x in nums] and [x for x in nums if x > 0]?

🧠 Quiz — Q3

How do you flatten a 2D list [[1,2],[3,4]] with a comprehension?

🧠 Quiz — Q4

When should you use a plain for loop instead of a comprehension?