Advertisement
Beginner Python, Comprehensions & Generators

How do you write a basic list comprehension, and how does it compare to an equivalent for loop?

Short answer

A list comprehension `[expr for item in iterable]` builds a new list in one concise expression, evaluating 'expr' for each item — functionally equivalent to a for loop that appends to a list, but generally more readable and slightly faster since it avoids repeated append()…

Save Python mock interview
Advertisement
AModel answer
A list comprehension `[expr for item in iterable]` builds a new list in one concise expression, evaluating 'expr' for each item — functionally equivalent to a for loop that appends to a list, but generally more readable and slightly faster since it avoids repeated append() method calls.
squares = [n * n for n in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

# Equivalent for loop:
squares2 = []
for n in range(5):
    squares2.append(n * n)
Real-world example
Quickly transforming a list of raw values (like strings) into a list of processed values (like their uppercase forms).
Likely follow-ups
  • How do you add a conditional filter to a list comprehension?
Related topics