Python List Comprehensions Tutorial
List comprehensions in Python are a great feature but also a little hard to wrap your head around at first. Basically a list comprehension is a one line for loop that outputs a list.
Let’s see a simple example. Suppose we wanted to output a list of five numbers, 0-4. If we use Python’s built-in range function we can do this with a simple
With a list comprehension, we can write this in one line:
Powerful, right? But also a little confusing still since we haven’t described how the first “x” in our list comprehension differs from the second “x”. So let’s use square the numbers from 0-4 to see how position matters:
Or with a list comprehension:
Our output expression comes first, in this case
x**2, followed by a for clause around our variable,
x, and then our input sequence,
For beginners, the multiple “x”s here can be confusing, so let’s show what happens if the output expression and the variable are not the same thing. Here we’ve changed the output expression to
a**2 and the variable to
We get a TypeError because we’re trying to do an operation on something that doesn’t exist.
But if we changed the variable and output expression to match, things will work, regardless of what we call them.
Finally, let’s get crazy and call our variable
this_could_be_anything to drive the point home further.
Still works, see?
There’s much more we can do with list comprehensions, especially around nesting. Now that we’ve covered the basics, the official Python docs which cover this all in detail will hopefully make more sense!
Want to improve your Python? I have a list of recommended Python books.