Python Comprehensions
Learn how list, set, and dictionary comprehensions build collections from iterables with concise, readable expressions.
Intermediate
A comprehension builds a collection by combining a value expression with one or more for clauses and optional if filters. Python has list comprehensions, set comprehensions, and dictionary comprehensions. They are useful when the result can be expressed clearly as a small transformation or selection.
Start with a list comprehension
A list comprehension uses square brackets. Read it from left to right: produce this value for each item in this iterable.
numbers = range(1, 6)
squares = [number * number for number in numbers]
print(squares)The expression before for determines what goes into the new list. The for clause supplies each value used by that expression.
Filter with if
Add an if condition after the for clause when only some items should contribute to the result. The condition is a filter; it does not change the value expression.
numbers = range(1, 8)
evens = [number for number in numbers if number % 2 == 0]
print(evens)This is a compact form of a loop that tests each item and appends only the items that pass the condition. Keep the loop form when the transformation or conditions become difficult to read.
Transform values
A comprehension can call functions, use methods, or perform other expressions to create a different value for each item.
names = [" Ada", "Grace ", " Guido "]
clean_names = [name.strip() for name in names]
print(clean_names)Build sets and remove duplicates
A set comprehension uses braces with the same expression-for-if shape. The resulting set keeps only unique values, just like any other set.
word = "banana"
letters = {letter for letter in word}
print(letters)Sets are unordered, so do not rely on a particular printed order. The useful guarantee here is uniqueness, not display order.
Build dictionaries
A dictionary comprehension uses a key expression, a colon, and a value expression before the for clause. It creates a new dictionary from the generated key-value pairs.
numbers = range(1, 5)
squares = {number: number * number for number in numbers}
print(squares)Dictionary keys must obey the normal dictionary-key rules. If a comprehension produces the same key more than once, the later value for that key replaces the earlier value.
More than one for clause
A comprehension can contain additional for clauses. They nest from left to right, so the later clause runs inside the earlier one. Use this when the relationship is clearer as a compact expression.
pairs = [(left, right)
for left in [1, 2, 3]
for right in [3, 1, 4]
if left != right]
print(pairs)Comprehensions have their own iteration scope
The iteration variable in a comprehension does not leak into the surrounding scope. This is different from a normal for loop, whose target name remains bound after the loop finishes.
number = 100
squares = [number * number for number in range(3)]
print(squares)
print(number)The comprehension's number is separate from the surrounding number. This scope behavior is part of Python's comprehension semantics, not just a style convention.
Choose clarity over cleverness
Comprehensions are best when the expression and filtering logic can be understood quickly. If you need several unrelated steps, side effects, complicated branching, or debugging inside the process, a normal for loop is often clearer.
# Clear comprehension
squares = [number * number for number in range(5)]
# Clear loop when several actions are needed
results = []
for number in range(5):
square = number * number
if square > 5:
results.append(square)
print(squares)
print(results)Comprehensions and generator expressions are different
A list comprehension creates a list immediately. A generator expression uses parentheses and produces a generator iterator whose values are produced during iteration. The generator-expression lesson covers that lazy behavior in detail.
numbers = range(1, 4)
list_result = [number * number for number in numbers]
generator_result = (number * number for number in numbers)
print(list_result)
print(list(generator_result))Key takeaways
- List comprehensions use square brackets to build lists.
- Set comprehensions use braces to build sets; duplicate results are removed by normal set semantics.
- Dictionary comprehensions use key: value expressions to build dictionaries.
- A comprehension can transform, filter, and combine iterables with for and if clauses.
- Comprehension iteration variables have their own implicit scope and do not leak into the surrounding scope.
- Use a normal loop when it communicates a multi-step operation more clearly.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.