NotesPythonData Structures

Comprehensions

Building lists, dicts, and sets in one readable line instead of a loop + append.

A comprehension builds a new collection from an existing iterable in a single, declarative expression — Python code tends to favor these over an explicit loop when the logic is simple.

List comprehensions

squares = [n * n for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]

titles = ["intro", "variables", "loops"]
capitalized = [t.title() for t in titles]
print(squares, evens, capitalized)

The general shape is [expression for item in iterable if condition] — the if part is optional.

The loop this replaces

# equivalent to the squares comprehension above
squares = []
for n in range(10):
    squares.append(n * n)

Comprehensions are usually both more concise and measurably faster than the loop-and-append version, because the append calls are optimized internally.

Dict and set comprehensions

Same idea, different brackets:

videos = ["Intro", "Variables", "Loops", "Functions"]
lengths = {v: len(v) for v in videos}          # dict comprehension
print(lengths)   # {'Intro': 5, 'Variables': 9, ...}

unique_lengths = {len(v) for v in videos}       # set comprehension
print(unique_lengths)

Nested comprehensions

Useful, but readability drops fast past one level of nesting — if it's hard to read, write the loop instead.

grid = [[1, 2, 3], [4, 5, 6]]
flattened = [num for row in grid for num in row]
print(flattened)   # [1, 2, 3, 4, 5, 6]

When not to use one

If the expression needs multiple statements, side effects, or more than one if/elif branch of logic, a comprehension becomes a puzzle instead of a shortcut — write a regular for loop instead. Readability wins over cleverness.

Key points to remember
  • The shape is [expression for item in iterable if condition] — the if is optional.
  • Comprehensions usually beat an equivalent loop + append in both readability and speed.
  • {k: v for ...} builds a dict, {v for ...} builds a set — same syntax family as list comprehensions.
  • Nested comprehensions (looping over a grid) work but hurt readability fast — don't go past one level if you can avoid it.
  • If the logic needs multiple statements or complex branching, write a plain for loop instead — clarity beats compactness.

List, dict, and set comprehensions side by side

Revision Flashcards

1 / 3

Tap a card to flip it and see the answer.