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

List Comprehensions & Generator Expressions

python Python 2.0+ Beginner

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 26
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
3 pings W 0 pings T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 0 pings S 1 ping S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Perplexity 6 Amazonbot 6 ChatGPT 2 Google 2 Unknown AI 2 Ahrefs 2
crawler 20
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