← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

List Comprehensions & Generator Expressions

Python Python 2.0+ Beginner
debt(d3/e1/b1/t5)
d3 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'default linter catches the common case' (d3), since ruff/pylint/flake8 flag the for-append-loop pattern (C4xx rules) and can suggest comprehensions.

e1 Effort Remediation debt — work required to fix once spotted

Closest to 'one-line patch' (e1), per quick_fix: swap a for-loop-and-append for a single-line comprehension, or change [] to () for a generator.

b1 Burden Structural debt — long-term weight of choosing wrong

Closest to 'minimal commitment' (b1) — comprehensions are a localised syntactic choice with no architectural weight or cross-codebase gravity.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap most devs eventually learn' (t5), grounded in the misconception: devs assume comprehensions are always more readable, but deeply nested/conditional ones become unreadable, and using a list comp instead of a generator silently materialises large datasets in memory.

About DEBT scoring →

Also Known As

list comprehension Python list comp dict set comprehension

TL;DR

Compact syntax for creating lists — [x*2 for x in range(10) if x%2==0] — and lazy generators that avoid materialising the full sequence.

Explanation

List comprehensions: [expr for item in iterable if condition] — evaluated eagerly, returns a list. Dict comprehensions: {k: v for k, v in items.items()}. Set comprehensions: {x for x in items}. Generator expressions: (expr for item in iterable) — identical syntax with parentheses, evaluated lazily, returns an iterator — no memory allocation for the full sequence. Use generators for large datasets: sum(x*x for x in range(10**9)) never builds the list. Nested comprehensions: [[cell for cell in row] for row in matrix]. PHP equivalents: array_map + array_filter for list comprehensions; PHP generators (yield) for the lazy equivalent. Python comprehensions are idiomatic and faster than equivalent for-loop constructions for pure expression transformations.

Common Misconception

List comprehensions are always more readable than equivalent loops. Simple comprehensions are clearer; complex multi-level comprehensions with conditions become unreadable. A well-named for loop is preferable to a comprehension that requires mental parsing to understand.

Why It Matters

List comprehensions express map and filter operations in a single readable line — replacing verbose for-loop-and-append patterns with Python's idiomatic, optimised syntax.

Common Mistakes

  • Multi-line comprehensions that are harder to read than the equivalent for loop — use a loop for complex logic.
  • Side effects inside comprehensions — comprehensions should be pure transformations.
  • Nested comprehensions deeper than two levels — extract a named function or use loops.
  • Using a list comprehension when a generator expression would avoid materialising the full list.

Code Examples

✗ Vulnerable
# Manual loop — verbose:
squares = []
for x in range(10):
    if x % 2 == 0:
        squares.append(x ** 2)

# List comprehension — idiomatic:
squares = [x ** 2 for x in range(10) if x % 2 == 0]

# Generator for one-time use:
total = sum(x ** 2 for x in range(10) if x % 2 == 0)
✓ Fixed
# List comprehension — concise, often faster than for-loop
squares   = [x**2 for x in range(10)]
evens     = [x for x in range(20) if x % 2 == 0]
flattened = [n for sublist in matrix for n in sublist]

# Dict comprehension:
word_count = {word: len(word) for word in ['apple', 'banana', 'cherry']}

# Set comprehension:
unique_lengths = {len(word) for word in ['apple', 'banana', 'cherry']}

# Generator expression — lazy, memory-efficient (no [])
total = sum(x**2 for x in range(1_000_000))  # doesn't build a list in memory

# When NOT to use comprehensions:
# - Complex nested logic — use a for-loop for readability
# - Side effects (e.g. printing) — for-loop is clearer
# - More than 2 conditions — extract to a function

Added 15 Mar 2026
Edited 22 Mar 2026
Views 50
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 1 ping W 1 ping T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 1 ping W 2 pings T 0 pings F 1 ping S 3 pings S 1 ping M 1 ping T 0 pings W 1 ping T 1 ping F 1 ping S 0 pings S 0 pings M 1 ping T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 1 ping M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Scrapy 9 Amazonbot 7 Perplexity 6 Ahrefs 4 Google 3 SEMrush 3 ChatGPT 2 Unknown AI 2 Claude 1 Meta AI 1 Bing 1 PetalBot 1
crawler 39 crawler_json 1
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Use list comprehensions for simple transforms ([x*2 for x in items]) and generator expressions for large datasets ((x*2 for x in items)) — they're more Pythonic than loops building lists
📦 Applies To
python 2.0 web cli
🔗 Prerequisites
🔍 Detection Hints
result = []; for x in items: result.append(transform(x)) — rewrite as list comprehension; loading entire large dataset into list when generator would suffice
Auto-detectable: ✓ Yes pylint ruff flake8
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✓ Auto-fixable Fix: Low Context: Function


✓ schema.org compliant