Skip to content
Python

Python Comprehensions Explained (List, Dict, Set)

By The EbookWale Team · Updated June 16, 2026 · 4 min read

Comprehensions build a list, dict, or set in one readable line. Here's how Python list, dictionary, and set comprehensions work — with filtering, nesting, and when they help versus hurt readability.

A comprehension builds a list, dictionary, or set in a single readable line by transforming (and optionally filtering) an iterable. It’s the most recognisable Python idiom — [n * n for n in range(5)] replaces a three-line loop — and writing comprehensions fluently is a hallmark of Pythonic code.

They’re a Phase 3 skill in the Python roadmap. Here’s all three forms and when to use them.

[ n * n for n in nums if n > 0 ] transform loop filter
Every comprehension: an expression, a loop, and an optional filter.

List comprehensions

The form is [expression for item in iterable if condition]:

squares = [n * n for n in range(5)]            # [0, 1, 4, 9, 16]
evens = [n for n in range(10) if n % 2 == 0]   # [0, 2, 4, 6, 8]
names = [u.name for u in users if u.active]    # transform + filter

Read it left to right: the expression, for each item, if a condition holds. It replaces the loop-and-append pattern:

# The long way comprehensions replace:
squares = []
for n in range(5):
    squares.append(n * n)

Dict comprehensions

Same idea, building a dictionary with key: value:

squares = {n: n * n for n in range(5)}         # {0: 0, 1: 1, 2: 4, ...}
prices = {p.name: p.cost for p in products}    # from objects
swapped = {v: k for k, v in original.items()}  # invert a dict

Set comprehensions

Curly braces without a colon, producing a set of unique values:

unique_lengths = {len(word) for word in words}   # a set, deduped

See lists vs tuples vs sets vs dicts for which collection you actually want.

Filtering and conditionals

The trailing if filters (decides whether to include an item). An if/else in the expression part transforms (chooses the value):

# Filter: only evens
[n for n in nums if n % 2 == 0]

# Transform: label each number (note the different position)
["even" if n % 2 == 0 else "odd" for n in nums]

Mixing these up is the most common comprehension confusion: a filtering if goes at the end; a transforming if/else goes at the start.

🔑 REMEMBER — Filter if goes at the end (… for x in xs if cond); transform if/else goes at the start (a if cond else b for x in xs). One decides whether to include; the other decides what value to produce.

Nested comprehensions (use sparingly)

You can nest, e.g. to flatten a 2D list:

flat = [x for row in matrix for x in row]   # read like nested for-loops

But nesting more than one level quickly becomes unreadable — at that point, a normal loop is clearer.

When a comprehension helps vs hurts

  • Use one for a simple transform/filter that fits comfortably on one line.
  • Use a regular loop when the logic is complex, has side effects, or won’t fit readably — clarity beats cleverness.
  • Use a generator expression (parentheses instead of brackets) for large data you only iterate once, to save memory.

Common mistakes

  • Putting a filtering if in the wrong place (see the callout).
  • Cramming complex logic into a comprehension until it’s unreadable — switch to a loop.
  • Building a huge list when a generator expression would do — wastes memory.
  • Side effects inside comprehensions (calling functions for their effect) — comprehensions are for building collections, not doing work.

Where this fits

Comprehensions are Phase 3 of the Python roadmap, closely tied to generators (the lazy cousin) and the collection types they build.

They’re introduced with worked examples in Python in One Month and used throughout the job-ready Python in Three Months.

Reach for a comprehension when it makes a simple transform clearer — and a loop when it doesn’t.

Frequently asked questions

What is a list comprehension in Python?

A list comprehension is a concise way to build a list in one line by transforming and optionally filtering an iterable. For example, [n * n for n in range(5)] produces [0, 1, 4, 9, 16]. It replaces a multi-line for-loop that appends to a list, and is considered the idiomatic Pythonic style.

What is the syntax of a Python comprehension?

The form is [expression for item in iterable if condition]. The expression is what each element becomes, the for clause iterates, and the optional if clause filters. Swapping the brackets gives a set comprehension {…} or, with key: value, a dictionary comprehension {k: v for …}.

What is the difference between a list comprehension and a generator expression?

A list comprehension uses square brackets and builds the entire list in memory immediately. A generator expression uses parentheses and produces values lazily, one at a time, using almost no memory. Use a list comprehension when you need the list; use a generator expression for large data you only iterate once.

Are comprehensions faster than for loops in Python?

Usually slightly faster, because the looping happens in optimised C internally rather than in Python bytecode, and they avoid repeated append calls. But the main benefit is readability and conciseness for simple transformations. For complex logic, a regular loop is clearer and the speed difference is minor.