Chapter 2. Creating Collections with Comprehensions

A list comprehension is a high-level, declarative way to create a list. It looks like this:

>>> squares = [ n*n for n in range(6) ]
>>> print(squares)
[0, 1, 4, 9, 16, 25]

This is essentially equivalent to the following:

>>> squares = []
>>> for n in range(6):
...     squares.append(n*n)
>>> print(squares)
[0, 1, 4, 9, 16, 25]

Notice that in the first example, what you type is declaring what kind of list you want, while the second is specifying how to create it. That’s why we say it is high-level and declarative: it’s as if you are stating what kind of list you want created, then letting Python figure out how to build it.

Python lets you write other kinds of comprehensions than lists. Here’s a simple dictionary comprehension, for example:

>>> blocks = { n: "x" * n for n in range(5) }
>>> print(blocks)
{0: '', 1: 'x', 2: 'xx', 3: 'xxx', 4: 'xxxx'}

This is equivalent to the following:

>>> blocks = dict()
>>> for n in range(5):
...     blocks[n] = "x" * n
>>> print(blocks)
{0: '', 1: 'x', 2: 'xx', 3: 'xxx', 4: 'xxxx'}

The main benefits of comprehensions are readability and maintainability. Most people find them very readable; even developers encountering a comprehension for the first time will usually find their first guess about what it means to be correct. You can’t get more readable than that.

And there is a deeper, cognitive benefit: once you’ve practiced with comprehensions a bit, you will find you can write them with very little ...

Get Powerful Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.