DEV Community

Mozart Maia
Mozart Maia

Posted on

Python's Secret Weapon: List Comprehension

If you are used to make programs or scripts in Python, you know the language has many ways to deal with collections. It's possible to iterate over a list (access the elements within a list) using for loops by index, as shown here:

for loop in python

Another way to do this with basically the same results is with a while loop:

while loop in python

If the only thing you need is the elements of the list, without the index, you can iterate using a simpler syntax:

for loop in python without index

The while loop in most cases might be slower than the for loops, because its running other statements, like the increment of variable counter and checking if the counter is still smaller than the size of my_list.

However, python offers another method to iterate over lists faster than both and without using libraries like Numpy. This is List Comprehensions. In this article from freeCodeCamp, we have a great definition:

List comprehension is an easy to read, compact, and elegant way of creating a list from any existing iterable object. Basically, it's a simpler way to create a new list from the values in a list you already have.

I couldn't say it better. List comprehensions can be a bit confusing for new programmers, especially those who have only learned imperative programming, because it uses declarative paradigm. I won't go into details of declarative/functional programming paradigms, but they are interesting ways of programming and it's worth exploring them as well.

So how we do this list comprehension thing? Let's break it down step by step with this image:
list comprehension in python

First we have a square bracket, the beginning of the list we are generating. Then in blue we have the elements of our list and any transformations we want to do with them, in this case we are multiplying each one for two.

Second in yellow we have the for loop where we will iterate over a list. We could use a variable holding a list, but to keep simple I created one using the function range(10), which give me a sequence from 0 to 10 (excluding the last).

Finally, in green is the condition we want to apply in the elements of the list. In this case, you can think of it as filtering our list, where we are verifying if the division of x by 2 (using the modulo operator - %) is equal to zero. In other words, if the number is even.

The result of this is the following list:

result of list comprehension

As a final exercise, let's create a simple program to find out if a number is prime or not using list comprehension. If you want, you can try it on your own and then check after if your answer is similar to mine.

Image description

I hope you liked this little article. Happy coding! :)

Top comments (0)