Comprehensions

Comprehensions condense for loops into a one-line expression.

List Comprehensions

A list comprehension creates a list:

squares = [x ** 2 for x in range(10)]

Produces the same result as:

squares = []
for x in range(10):
    squares.append(x ** 2)

Conditionals

The comprehension may contain an if clause to filter the list:

squares = [x ** 2 for x in range(10) if x % 3 == 0]

Note that you can also place an if on the other side of the for as a ternary expression. This leads to a different result:

squares = [x ** 2 if x % 3 == 0 else -1 for x in range(10)]

Nested Comprehensions

It is perfectly fine to place one comprehension inside another. The following code creates a 5x5 matrix:

[[x * y for x in range(5)] for y in range(5)]

Note that you can concatenate the for statements without the extra brackets. In that case the result is a flat list:

[x * y for x in range(5) for y in range(5)]

The join pattern

Comprehensions that produce a list of strings are often found together with join(), e.g. to format text output:

';'.join([char.upper() for char in 'abcde'])

Dict comprehensions

This variant produces dictionaries:

ascii_table = {x: chr(x) for x in range(65, 91)}

Set comprehensions

The same with a set:

unique = {x.upper() for x in 'Hello World'}

Dr. Kristian Rother

I am a professional Python trainer, developer and author based in Berlin. I believe everybody can learn programming.

Contact me via:
+49 176 3052 4691
krother@academis.eu

Feedback

I want to really thank you! I got a lot of very nice compliments, such as: "Well done, I had a lot of fun". And people were smiling during the talk!!!

Allegra Via, Sapienza University Rome

See also