List Comprehension in Python (With Examples)

Let's start off by defining what the heck is list comprehension?  And why is it so cool?  Well, list comprehension helps you build a list based on existing lists.  Admit it, we've all been there.

Perhaps the list you're dealing with is multidimensional and you only want a certain aspect of the data inside. And even then you want to filter results. Let's take a look at a couple of examples.

And we're assuming you're using Python 3

Let's say you have this two-dimensional list.


mylist = [
    [0,2,4,6,8,10],
    [1,3,5,7,9,11],
    [10,20]
]

And you want to get all the values from the nested lists that are less than 6.  OK, you may be thinking I'll just loop over the list and fill a new list I previously created.


newlist = []

#Loop both dimensions of the list
for i in mylist:
    for p in i:
        if p < 6:
            newlist.append(p)

print(newlist)
# [0, 2, 4, 1, 3, 5]


Yuck. Don't do this. The reason we love Python is that it makes our lives simple. We want less code. One-liners are great. So take a look at how Python allows us to do this using list comprehension.


newlist = [i for p in mylist for i in p if i < 6]
print(newlist)
# [0, 2, 4, 1, 3, 5]

So to explain this, think of it like this:

new_list = [expression(i) for i in old_list if filter(i)]

Magic right?  But what if it's just a simple list like:


mylist = [0,2,4,6,8,10]

And we want to get the values less than 6. Even easier:


newlist = [i for i in mylist if i < 6]
print(newlist)
# [0, 2, 4]

Enjoy!

Pingbacks are closed.

Comments are closed.