πŸ’½List Comprehensions

Loops over lists!

Our journey with lists ends with using the structure and knowledge we've developed about lists to create a very powerful tool β€”Β list comprehensions. List comprehensions are a combination of for loops and lists.

We'll start developing our understanding of list comprehensions with the following piece of code:

lst = []
for i in range(5):
    lst.append(i*2)

After executing the following code, the list lst would look like [0, 2, 4, 6, 8]. As you'll realize with further excursions into Python, this is a very common pattern that emerges time and again β€”Β looping over some values, and adding them to a list after updating them in some way. This is so common, in fact, that Python developed native syntax for us to be able to use to perform this. It looks something like this:

lst = [i*2 for i in range(5)]

The above statement gets us to the same values as the first code block. This is a list comprehension.

There are a few other things you can do with them β€”Β you could add an if statement!

lst = [i for i in range(10) if i % 2 == 0]

This only adds the even numbers [0, 2, 4, 6, 8] to our list lst.

As you probably realize, list comprehensions are much less flexible than for loops. In a for loop, you can add multiple lines of code β€” only one line of code within the for loop is possible in list comprehensions. In a for loop, you could do other "side-effects" like say a print statement β€”Β the only thing the list comprehension can do is the expression for the value that will be added to the list.

List comprehensions are therefore excellent syntactic sugar β€” that is to say, they look nice, they are easy to write, and they make sense to our English loving human brains, but they don't give us any new powers in Python that we didn't already have.

Last updated