Collections

Comprehensions

Comprehensions build collections by mapping and filtering iterables.

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']
A comprehension is a compact spelling of the equivalent for-loop with append, made into one expression.

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

See also

Run the complete example

Example code

Expected output

['Ada', 'Guido', 'Grace']
{'Ada': 10, 'Grace': 10}
[8, 10]

Execution time appears here after you run the example.