Python - List Comprehensions

Personally, I think this is one of the most powerful features of Python. The ability to literally shrink multiple lines of code into a single, concise, easily readable statement.

A list comprehension is normally written with brackets [] containing an expression followed by a for clause. Then zero or more for or if clauses.

The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which immediately follows the expression. For example, this list comprehension combines the elements of two numeric lists if and when the variables are not equal:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and this single statement:

[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

is equivalent to:

>>> jellybeans = []
>>> for x in [1, 2, 3]:
...   for y in [3, 1, 4]:
...     if x != y:
...       print((x-y))
...
>>> jellybeans
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

List comprehensions can contain multiple complex expressions and nested functions. Just look at how concise this reads.

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1,4)]
['3.1', '3.14', '3.142']

The following list comprehension will transpose rows and columns:

>>> num_list = [
...  [1, 2, 3, 4],
...  [5, 5, 7, 8],
...  [9, 10, 11, 12],
]
>>> [[row[i] for row in num_list] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Which can also be written as:

>>> r = []
>>> for i in range(4):
...   r.append([row[i] for row in num_list])
...
>>> r
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Which unbelievably, is equivalent to this much longer statement:

>>> r = []
>>> for i in range(4):
...       r_row = []
...       for row in num_list:
...         r_row.append(row[i])
...         r.append(r_row)
...
>>> r
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Pretty neat, huh? You can easily see why List comprehensions are one of Python's most powerful features.

Craig Derington

Espousing the virtues of Secular Humanism, Libertarianism, Free and Open Source Software, Linux, Ubuntu, Terminal Multiplexing, Docker, Python, Flask, Django, Go, MySQL, PostgreSQL, MongoDB and Git.

comments powered by Disqus