Comprehensions

A comprehension builds a new collection from an existing one.

Output:

[1, 4, 9]

Read it as:

For each number in numbers, compute number squared, and collect the results in a new list.

Loop First, Then Comprehension

This loop:

can be written as:

squares = [number ** 2 for number in numbers]

Use the loop form when the transformation needs several steps. Use the comprehension when the transformation is short and readable.

Loop and comprehension

Both versions build the same list.

Runs locally with Python in your browser.

Ready to run.

Filtering

Add an if clause to keep only some items:

Output:

[4, 16]

The if keeps even numbers before squaring them.

Dictionary Comprehensions

Dictionaries can be built this way too:

Output:

{1: 1, 2: 4, 3: 9}

Keep Comprehensions Readable

Do not make a comprehension so dense that it becomes hard to read. A clear loop is better than a clever one-line transformation.

Exercise: Build squares

What list does this comprehension create?

[n * 2 for n in [1, 2, 3]]

Answer it first, then check.

HintTransform one item at a time

Substitute 1, then 2, then 3 for n in n * 2.

SolutionEach item is doubled

The three computations are 1 * 2, 2 * 2, and 3 * 2. The new list is [2, 4, 6].

Comprehensions Build Collections from Patterns

Comprehensions are compact loops. Use them when they make a simple transformation clearer.