Skip to content

Comprehensions Intro

A comprehension is a compact syntax for building a new list, dict, or set by transforming and optionally filtering an existing iterable β€” in one expression instead of a multi-line for loop. They exist for lists ([...]), sets ({...}), and dicts ({k: v for ...}).

# List comprehension
squares = [n * n for n in range(6)] # [0, 1, 4, 9, 16, 25]
# With a filter condition
evens = [n for n in range(10) if n % 2 == 0] # [0, 2, 4, 6, 8]
# Dict comprehension
lengths = {word: len(word) for word in ["hi", "hello", "hey"]}
# {'hi': 2, 'hello': 5, 'hey': 3}
# Set comprehension
unique_lengths = {len(word) for word in ["hi", "hey", "yo"]} # {2, 3}

Writing a comprehension so dense with nested loops or conditions that it becomes harder to read than the plain for loop it replaced β€” comprehensions are for simple transform/filter operations, not everything.

# Hard to read -- nested loop, unclear intent
result = [x*y for x in range(5) for y in range(5) if x != y if (x+y) % 2 == 0]
# Clearer as a regular loop
result = []
for x in range(5):
for y in range(5):
if x != y and (x + y) % 2 == 0:
result.append(x * y)
  1. What’s the difference between [x for x in items] and {x for x in items}?

    AnswerThe first builds a list (ordered, duplicates allowed); the second builds a set (unordered, duplicates automatically removed).
  2. How do you filter items inside a comprehension?

    AnswerAdd an if condition at the end: [x for x in items if condition].
  3. When should you prefer a regular for loop over a comprehension?

    AnswerWhen the logic involves multiple nested conditions/loops or side effects (like printing or writing to a file) β€” comprehensions should stay simple and side-effect-free.