List Comprehensions

Mar 30, 2021

I initially thought Python list comprehensions were obtuse and unnecessary, a bit of syntactic sugar I didn’t need, but after spending more time with them my opinion has completely flipped. Now I not only use them as much as I can, but I also want to get the word out for those who might not know about them.

Let’s start with a simple example. Let’s say I want to alter all the items in a list using a function and generate a new list. Our list will be x and our function will be sqrt from the math module.

First up is the straightforward method using a for loop.

>>> from math import sqrt
>>> x = range(1000)
>>> y = []
>>> for i range x:
...     y.append(sqrt(i))
>>> y[:5]
[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979]

Now here’s the same example using list comprehension.

>>> y = [sqrt(i) for i in x]
>>> y[:5]
[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979]

List comprehension is simply a set of brackets containing an expression followed by a for clause.

Additionally, one or more if clauses can be added to a list comprehension.

>>> z = [sqrt(i) for i in x if i > 50]
>>> z[:5]
[7.14142842854285, 7.211102550927978, 7.280109889280518, 7.3484692283495345, 7.416198487095663]

List comprehension also allows for the simple creation of lists on the fly, let’s say 1000 random floats.

>>> import random
>>> floats = [random.random() for _ in range(1000)]
>>> floats[:5]
[0.7780346266380861, 0.6197484726418738, 0.8439569186352499, 0.21261969119693835, 0.1844600543795476]

I will continue to use list comprehensions, one more tool to integrate in my Python toolbox. I hope you agree list comprehensions are great, but part of the reason I wanted to talk about them was in order to build up to generators and generator comprehensions. Stay tuned.