Collections

Comprehensions

Comprehensions build collections by mapping and filtering iterables.

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']
[x*2 for x in xs if x > 0]out = []for x in xs: if x > 0: out.append(x*2)
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.

Source

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