What is a list comprehension in Python, and how does it differ from a generator expression?
py-jun-004
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
A list comprehension [expr for x in iterable if condition] evaluates eagerly — it creates the entire list in memory immediately. A generator expression (expr for x in iterable if condition) is lazy: it produces values one at a time on demand and holds only one item in memory at a time. Use list comprehensions when you need random access, len(), or multiple passes over the result. Use generator expressions when you only need to iterate once, especially over large datasets — they use O(1) memory instead of O(n). You can pass a generator expression directly to functions that accept iterables (sum, max, any, all) without the extra parentheses in some cases.
Code example
# List comprehension — eager, full list in memory
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # [0, 4, 16, 36, 64]
print(len(squares)) # OK — list supports len()
# Generator expression — lazy, one value at a time
gen = (x**2 for x in range(10) if x % 2 == 0)
print(next(gen)) # 0
print(next(gen)) # 4
# Memory comparison for large datasets
import sys
lst = [x for x in range(1_000_000)]
gen = (x for x in range(1_000_000))
print(sys.getsizeof(lst)) # ~8 MB
print(sys.getsizeof(gen)) # ~200 bytes
# Pass generator directly to sum
total = sum(x**2 for x in range(1000)) # no intermediate list
# Dict + set comprehensions
word_lengths = {word: len(word) for word in ["python", "go", "rust"]}
unique_evens = {x % 10 for x in range(100)}
Follow-up
What is a dictionary comprehension, and how would you invert a dict {k: v} -> {v: k} in a one-liner?