Skip to main content
Albero Academy

Comprehensions

Build lists, dicts and sets in one readable expression — a signature Python idiom.

Data Structures10 min

A comprehension builds a collection from an iterable in a single, readable expression. It's one of Python's signature idioms — replacing a three-line "create empty list, loop, append" pattern with one clear line, and it's often faster too.

List comprehensions

The shape is [expression for item in iterable]. Compare the loop and the comprehension:

from loop to comprehension
# The long way
squares = []
for n in range(6):
squares.append(n * n)
# The comprehension — same result, one line
squares = [n * n for n in range(6)] # [0, 1, 4, 9, 16, 25]

Filtering & transforming

Add an if to keep only some items, and put any expression on the left to transform them:

filter and map together
evens = [n for n in range(10) if n % 2 == 0] # [0,2,4,6,8]
names = ["ana", "ravi"]
caps = [name.upper() for name in names] # ['ANA', 'RAVI']
# Conditional expression on the left (map every item)
labels = ["pass" if s >= 40 else "fail" for s in scores]

Dict & set comprehensions

The same idea builds dicts and sets — just change the brackets:

beyond lists
# dict comprehension {key: value for ...}
lengths = {w: len(w) for w in ["hi", "there"]} # {'hi': 2, 'there': 5}
# set comprehension {expr for ...}
first_letters = {name[0] for name in names} # unique first letters
# generator expression (lazy) — parentheses instead of brackets
total = sum(n * n for n in range(1000)) # no list built

Key takeaways

  1. 01A comprehension builds a collection in one expression: [expr for x in iterable].
  2. 02Add if to filter; put an expression (or ternary) on the left to transform.
  3. 03The same syntax builds dicts {k: v for …} and sets {expr for …}.
  4. 04(expr for …) is a lazy generator expression — memory-efficient for large data.
  5. 05Keep them simple — fall back to a loop when the logic gets complex.

Finished this chapter?

Mark it complete to track your progress through Python.