List Comprehension

Joseph Hart
3 min readSep 16, 2020

--

Before learning about list comprehension, I suggest you learn about for loops and how they work. List comprehension is similar to a for loop in the sense that it will iterate over objects in a list.

List comprehension is great to simply lines of code and makes it easier to read. In this article, I’ll show you how to go from a for loop to list comprehension.

Let’s say we have this list:

In this list we have a few fruits that we want to iterate over and say we need them. In a for loop, we would write it as:

Instead we can write this as

Now in this case, you might think this is just as much work if not more than the for loop, and you would be right, until things get a little more intense.

Let’s say we have a second list of numbers and we want to iterate over which ones are even and which are odd. In a for loop it would look like this:

We see this gets a little more complex and takes more time to write and read. In list comprehension, it would be written as so:

In both examples we need to have list in front our our comprehension, otherwise we get a generator object.

List comprehension is a great tool and saves line of code making it easier to read. I hope this helps and you can use this in future projects.

--

--

No responses yet