🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Comprehensions: Nesting, Conditions, and Memory Costs

Python ComprehensionsđŸŸĸ Free Lesson

Prerequisites

  • !List, dict, and set literals
  • !for loops, conditions, and the difference between mapping and filtering

What You'll Learn

  • 1Read a nested comprehension in the correct evaluation order
  • 2Choose between filtering with if and mapping with a conditional expression
  • 3Switch to a generator expression when memory matters
  • 4Explain the single evaluation rule for loop variables
  • 5Decide when a comprehension has grown past the point of being readable

Comprehensions are the idiom most often copied without being understood. They are not syntactic sugar for any loop: they are a dedicated construct that the interpreter compiles into efficient iteration code, with fixed scoping rules and a clear distinction between building a result and streaming one. Used deliberately they compress several lines into one without losing clarity. Used carelessly they produce the kind of three-branch nested expression that nobody, including the author six weeks later, can parse.

What the interpreter does with a comprehension

A list comprehension allocates its result list up front and appends each produced element as the loop runs, which is why the CPython implementation is noticeably faster than an equivalent loop with append calls: the bytecode skips the attribute lookup for append on every iteration and works directly with the list internals. A dict or set comprehension does the same, except the container also handles hashing and deduplication as it goes, so a set comprehension is usually the shortest way to remove duplicates while preserving nothing about order.

python
words = ["  Ana", "bob ", "CARL", "dana ", "EVE"]

clean = [w.strip().title() for w in words]
by_length = {len(w): [x for x in clean if len(x) == len(w)] for w in clean}
unique_lengths = {len(w) for w in clean}

print(clean)            # ['Ana', 'Bob', 'Carl', 'Dana', 'Eve']
print(by_length[3])     # ['Bob', 'Eve']
print(sorted(unique_lengths))

The middle line shows a nested comprehension: an outer loop over clean builds keys, and an inner comprehension builds each value. It works, but the inner expression repeats a length calculation twice, which is a hint that the piece wants its own name rather than more nesting.

Reading nested comprehensions out loud

Evaluation runs left to right, exactly as a set of nested loops would, and the first clause is always a for. The safe translation procedure is mechanical: say each for in order as a loop, each if as a guard, and the leading expression as what gets appended. Doing this for a comprehension is faster than squinting at it, and it reliably exposes mistakes such as a guard applied to the wrong loop.

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

flat = [value for row in matrix for value in row]
print(flat)                       # [1, 2, 3, 4, 5, 6, 7, 8, 9]

above = [value for row in matrix for value in row if value > 4]
print(above)                      # [5, 6, 7, 8, 9]

paired = {(row[i], row[i + 1]) for row in matrix for i in range(len(row) - 1)}
print(sorted(paired))
# [(1, 2), (2, 3), (4, 5), (5, 6), (7, 8), (8, 9)]

Note that flattening is a two-loop comprehension, not a comprehension applied twice. The common beginner error is to write a loop over matrix and then try to index each row with a second expression inside the same clause, which produces rows rather than values. When a comprehension needs a computed index like i + 1, that is often the signal to switch back to a loop, because the arithmetic hides the intent.

Filtering, mapping, and conditional expressions

The if clause in a comprehension filters: nothing is produced for a rejected item. A conditional expression, written as the leading value with if and else, maps every item to one of two outputs. Confusing the two silently changes the length of your result.

IntentShapeResult lengthTypical use
Filter itemsfor x in xs if condAt most that of inputDrop nulls, keep active rows
Map with two branches"yes" if cond else "no"Same as inputLabel encoding
Map with a default[f(x) if x else d for x in xs]Same as inputSubstituting fallbacks
DeduplicateSet comprehensionUnknownUnique tags, unique keys
Build a lookupDict comprehensionUnknownIndex by id

Chaining two if clauses means both must pass, which is useful for combining constraints and surprising when written as a single condition with and in the wrong place. If you find yourself nesting conditional expressions more than one level deep, the version with an explicit helper function or an early-exit loop will be easier to test and far easier to debug.

Generator expressions: skipping the list on purpose

Round brackets instead of square ones produce a generator expression, which yields items lazily and never builds the whole result. Anywhere the loop consumes the values once and discards them, the generator is the better default: sum, min, max, any, all, sorted when you only need part of the result, and feeding a C API that accepts any iterable.

python
import heapq

raw = range(2_000_000)

total = sum(x * x for x in raw if x % 3 == 0)
first_pair = next(zip(raw, raw[1:]))
top_five = heapq.nsmallest(5, (x for x in reversed(raw)))

print(total % 1000)
print(first_pair)
print(top_five)

The trap is that a generator expression can only be consumed once and cannot be iterated twice. Code that builds a generator, then tries to len() it or walk it a second time, fails at runtime rather than at import time, which is exactly the kind of bug that survives code review. Two other limits apply: a generator expression allows only one for clause with conditions attached to it, and you cannot pick an element by index. If you need either, materialise deliberately with list() and a comment explaining why.

Scope, binding, and the rules that changed in Python 3

Comprehensions have their own implicit scope in Python 3, so the loop variable does not leak into the surrounding code. That is an improvement over Python 2, but it also means a comprehension cannot assign to a name outside itself, however tempting that looks. The related rule that catches people in loops is late binding in lambdas and closures: a comprehension evaluated immediately has no such problem, which is why it is the recommended way to capture a value inside a loop.

Another subtlety is that names in the iterable expression are evaluated in the enclosing scope before the new scope opens, while names in the result expression are evaluated inside it. This asymmetry explains why a comprehension can read the variable it is shadowing in one place and not the other. When you hit that, assign the outer value to a differently named local first; it costs one line and removes all doubt.

Where readability ends

The line at which a comprehension stops being an asset is roughly one loop with one condition. Two loops are acceptable when they are obviously independent, as in flattening. Two loops plus two conditions, or a conditional expression nested inside a condition, is the point where reviewers start translating line by line, and translation means the compression has backfired.

A practical discipline is to write the comprehension first when the logic is short, then measure it with the three questions: can you read it aloud in one pass, does each name mean one thing, and can you step through it in a debugger without invisible frames. If any answer is no, expand it into a loop with named intermediates. Performance almost never suffers, because the interpreter's loop is the same iteration underneath, and correctness improves immediately when each step has a name you can print.

Common Mistakes

Using a conditional expression when you meant to filter items out

Fix: Decide first whether the result should be shorter than the input; only a for clause with an if does that.

Reusing a generator expression twice or asking it for its length

Fix: Materialise it once into a list when you need multiple passes, and keep the generator when you only stream once.

Chaining three levels of nesting to save two lines

Fix: Extract a helper function for the inner transformation and keep the outer comprehension flat.

Building a giant dict comprehension inside a hot path without measuring

Fix: Profile both versions; if allocation dominates, stream with a generator or pre-size the container in a loop.

Best Practices

  • Read the comprehension aloud as nested loops before accepting it
  • Prefer one loop and one condition, and name the result when it is used twice
  • Use generator expressions for sums, any, all, and single-pass pipelines
  • Keep the result expression simple; move complex logic into a named function
  • Write the loop version first when the logic has branches, then compress if it stays clear

Key Takeaways

  • Comprehensions compile into dedicated iteration code, which is why they beat append loops
  • The leading expression plus for clauses reads in left-to-right loop order
  • if in a comprehension filters; a conditional expression maps and keeps the length
  • Generator expressions trade multiple passes and indexing for constant memory
  • Nesting depth is the real readability limit, not line length
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement