All concepts

Comprehensions

Build lists, dicts, and sets in one readable expression from an iterable + filter.

Python · Beginner · ~5 min

In plain English

Build a list, set or dict in one readable line instead of three lines of append-to-an-empty-container.

Why it's worth your time

It's the most idiomatic thing in Python, and knowing when NOT to use one is what separates readable code from clever code.

If you remember three things

  • [expr for x in it if cond] — map and filter in one
  • Dict and set comprehensions use the same shape
  • Generator expressions use () and stay lazy

Overview

A comprehension builds a collection in a single expression from an iterable, an optional filter, and a per-element transform. The same syntax builds lists ([...]), dicts ({k: v ...}), and sets ({x ...}). It's the idiomatic replacement for the empty-collection-plus-append loop, when the logic stays simple.

In an interview

A comprehension collapses the build-an-empty-collection-then-loop-and-append pattern into one expression: [f(x) for x in items if cond]. Switch the brackets to braces and you get dict and set comprehensions. It's more readable and usually faster than the manual loop for simple map-and-filter work—but once the logic nests deeply or has side effects, a plain loop is clearer. I also keep the four core containers straight: list is ordered and mutable, tuple is an immutable record, set holds unique items, dict maps keys to values.

Production defaults

Use when
the whole thing fits on one readable line
Don't
nest more than two levels, or hide side effects inside one. Write the loop
Large data
generator expression, not list comprehension — same syntax, flat memory

What breaks

  • Comprehension is unreadable — That's the signal to write an explicit loop. Comprehensions are for clarity, not for brevity points.
  • Memory spike building a big list — Use a generator expression if you only iterate once.

Watch it explained

Tutorial 17- Python List Comprehension — Krish Naik, 8:07

Related