Comprehension
In one line
A comprehension is a compact syntax for creating lists, dicts, or sets from an iterable in a single expression.
In simple words
A comprehension is a concise way to create a collection by transforming and/or filtering items from an iterable. It replaces a multi-line for loop with a single readable expression.
List comprehension: [expr for item in iterable if condition] Dict comprehension: {key: value for item in iterable} Set comprehension: {expr for item in iterable}
The optional if clause filters which items are included. Comprehensions are more Pythonic and often faster than equivalent for loops, but very complex comprehensions should be split into regular loops for readability.
Example
# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# With filter
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Dict comprehension
word_len = {w: len(w) for w in ["cat", "dog", "bird"]}
print(word_len) # {'cat': 3, 'dog': 3, 'bird': 4}Comprehensions create collections concisely with an expression, a loop, and an optional filter.
Common confusions
Confused with: lambda
The difference: A comprehension creates a collection by transforming items. A lambda creates an anonymous function. Comprehensions produce data; lambdas produce callable functions.
Related terms
Related Resources
Related Lessons
- List Comprehensions
Comprehensions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.