Collections
Comprehensions
Comprehensions are expression forms for building concrete collections from iterables. Read them from left to right: produce this value, for each item, optionally only when a condition is true.
They are best for direct transformations where the expression is still easy to scan. When the work needs several statements or names, an explicit loop is usually clearer.
List, dictionary, and set comprehensions are eager: they build collections immediately. Generator expressions use similar syntax to stream values later and are covered in the Iteration section.
A list comprehension maps each input item to one output item. This one calls title() for every name and collects the results in a new list.
Source
names = ["ada", "guido", "grace"]
titled = [name.title() for name in names]
print(titled)Output
['Ada', 'Guido', 'Grace']Add an if clause when only some items should appear. A dictionary comprehension can transform key/value pairs while preserving the dictionary shape.
Source
scores = {"Ada": 10, "Guido": 8, "Grace": 10}
high_scores = {name: score for name, score in scores.items() if score >= 10}
print(high_scores)Output
{'Ada': 10, 'Grace': 10}A set comprehension keeps only unique results. Here two people have the same score, so the resulting set has two values — printed through sorted() because sets have no display order to rely on.
Source
unique_scores = {score for score in scores.values()}
print(sorted(unique_scores))Output
[8, 10]Notes
- The left side says what to produce; the
forclause says where values come from. - Use an
ifclause for simple filters. - List, dict, and set comprehensions build concrete collections immediately.
- Switch to a loop when the transformation needs multiple steps or explanations.
See also
- prerequisite: For Loops
- next depth: Generator Expressions
- related: Comprehension Patterns
- related: Lists
Run the complete example
Expected output
['Ada', 'Guido', 'Grace']
{'Ada': 10, 'Grace': 10}
[8, 10]
Execution time appears here after you run the example.