โšกList, Dict & Set ComprehensionsLESSON

List, Dict & Set Comprehensions

Comprehensions are Python's concise syntax for building new collections from existing iterables. They are faster than equivalent for loops (the iteration is done in C under the hood) and, when kept simple, dramatically improve readability.

List Comprehension

Equivalent for loop for comparison:

Dict Comprehension

Set Comprehension

Nested Comprehensions

You can nest comprehensions to work with 2D structures. Keep readability in mind โ€” more than two levels is usually a sign to use a regular loop.

Filtering with if

The if clause comes at the end of the comprehension and acts as a filter โ€” only items passing the condition are included:

Walrus Operator (:=) in Comprehensions

Python 3.8+ allows capturing a sub-expression with := (walrus operator) to avoid computing it twice:

The walrus operator is especially useful when the filtering predicate and the value you want to keep are the same computation.

Performance: Comprehensions vs map/filter

Comprehensions are generally the preferred Pythonic style, but map/filter with simple callables can be marginally faster for very large datasets:

In practice the difference is small. Prefer comprehensions for readability unless profiling shows a bottleneck.

Readability Guidelines

Do use comprehensions when:

  • The logic is a simple transformation or filter
  • The result fits on one line (โ‰ค 79 characters)
  • There are at most two for clauses

Avoid comprehensions when:

  • The loop body has side effects (printing, writing to a file, modifying external state)
  • The logic is complex enough that a for loop with comments would be clearer
  • You need the overhead of exception handling inside the loop

Knowledge Check

What does [x for x in range(10) if x % 2 == 0] produce?

What is the correct syntax for a dict comprehension that maps each number to its cube for numbers 1-5?

In a nested list comprehension [elem for row in matrix for elem in row], which loop runs first (outermost)?