List Comprehensions, et al.

List comprehensions in Python are kinda funny to look at if you’ve never seen them before, and are certainly odd if you’re not familiar with for loops or control flow.

The way I approach list comprehensions (or dict, tuple, and set) comprehensions has to do with the basic for loop structure. Let’s take a simple for loop that iterates over a list of integers:

1
2
3
x = []
for item in [1, 3, 5, 7, 9]:
    x = x.append(item ** 2)

The output of this loop should be:

[1, 9, 25, 49, 81]

Now then, let’s turn this for loop into a list comprehension:

x = [item ** 2 for item in [1, 3, 5, 7, 9]]

The output of this will be:

[1, 9, 25, 49, 81]

So, as you can see the list comp allows the shortening of a simple for loop into a one-liner.

Let’s take is a step further. Let’s introduce a conditional into our for loop and see how that fits into our list comp.

x = []
for item in [1, 3, 5, 7, 9]:
    if item > 4: 
        x.append(item ** 2)

The output of which will be:

[25, 49, 81]

So in this for loop, we used an if statement to filter out of the iterable anything greater than 4. Let’s plug the same condition, or filter, into our list comp:

x = [item ** 2 for item in [1, 3, 5, 7, 9] if item > 4]

And as you should expect, our output is the same:

[25, 49, 81]

Once I saw the connection between list comprehensions and for loops, I came to love list comps for their simplicity and terseness.

Thanks for reading!