Collections
Comprehensions
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.
Source
unique_scores = {score for score in scores.values()}
print(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.