Python List Comprehensions in 5-minutes

Quick link: Jupyter Notebook on GitHubWhy would you want to do a Python list comprehension?To save lines of code.

There’s might be more to it than that but in my experience, this is the only reason — if you have a better one, leave a comment and I’ll update the article.

You can get the exact same thing done with a couple extra lines.

But browse any Python Stack Overflow question and chances are you’ll find someone asking for a Pythonic version or a Pythonic one-liner.

List comprehensions are a way of achieving Pythonic one-liners with iterables (lists).

One-line definitions:List = a Python object which can be iterated over (an iterable).

Iterated over = going through something one-by-one.

A good example is emptying your shopping cart at the cashier, you pull each item out one by one and put it on the counter, your shopping cart could be considered an iterable.

We’ll use this example to look at some code.

We’re shopping at a math store so all we’re buying is numbers.

# Create a list of numbers (our shopping cart)cart = [3, 4, 12, 17, 19, 21, 23, 26, 30]# Pass items to the cashiercashier = []for item in cart: cashier.

append(item)print(cashier)# The output is the same as the cartOutput: [3, 4, 12, 17, 19, 21, 23, 26, 30]What happened here?We created a list of items in the cartWe created an empty cashierlist (the cashierdidn’t have any of our items yet)We used a for loop to iterate over each itemin our cartFor each itemwe added it to the cashier list with .

append()Then we checked what items the cashier had with print()How could we do this same thing a list comprehension?# Pass items to second cashier but with a list comprehensioncashier_2 = [item for item in cart]print(cashier_2)# The output is the same as cashier (and the same as cart)Output: [3, 4, 12, 17, 19, 21, 23, 26, 30]What happened here?The exact same steps as above, only written in a different way.

Let’s compare.

A non-list comprehension and list comprehension comparison of the same code.

cashier is created in blue.

On the left, it’s created on its own line.

On the right, it’s created at the same time everything else is being created.

cart is being iterated over in green.

item is created as the for loop runs.

This step is the same as grabbing one item at a time out of your shopping cart and passing it to the cashier.

cashier is updated in the red with each item.

The only difference is on the left, an .

append() statement is required.

The list comprehension on the right negates the need for an .

append() statementWe accomplished the same steps in 1 line of code instead of 3.

This may not seem like much but say you had a 1000 line Python project.

You could potentially reduce your project from 1000 lines to 300.

This kind of reduction won’t always happen but it’s an example of how to get the same task done with a Pythonic one-liner.

What else can you do with Python list comprehensions?Now you’ve got a little bit of an intuition, let’s look at a few more examples.

cashier_3 only deals with even numbers.

How could we deal with this?By using a conditional.

Conditional = another way of saying, do something if True, stop if False.

# Make a new cartcart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Only give cashier_3 even numberscashier_3 = []for item in cart: if item % 2 == 0: cashier_3.

append(item)print(cashier_3)# Thanks to the conditional the output is only the even numbersOutput: [10, 12, 20, 22]How about with a list comprehension?cashier_3 = [item for item in cart if item % 2 == 0]print(cashier_3)# The output is the same as aboveOutput: [10, 12, 20, 22]What’s happening here?Example of a non-list comprehension and a list comprehension with a conditional.

This is similar to the above example except for the conditional in yellow.

cashier_3 is created in blue.

cart is being iterated over in green.

item is being created as the for loop runs.

As each item is passed to cashier_3, it’s being checked to see if it matches up with the conditional in yellow.

cashier_3 is updated in the red with each item as long as it fulfils the conditional in yellow.

Over 100 and oddcashier_4 only accepts numbers over 100 and are odd.

How could you do this?# Reminder of what cart looks likecart = [5, 7, 9, 10, 12, 15, 19, 20, 22]# Non-list comprehension for cashier_4cashier_4 = []for item in cart: item += 100 # add 100 to each item to bring them over 100 if item % 2 == 1: # check to see if they're odd or not cashier_4.

append(item)print(cashier_4)# The output is all odd numbers over 100Output: [105, 107, 109, 115, 119]Now with a list comprehension.

# List comprehension for cashier_4cashier_4 = [item+100 for item in cart if item % 2 == 1]print(cashier_4)# The output is all odd numbers over 100 (same as above)Output: [105, 107, 109, 115, 119]What’s next?This tutorial only scratches the surface of what’s possible with Python list comprehensions.

Once you start to get the hang of them, you’ll start to realise how valuable they are for writing succinct and powerful Pythonic code.

If you’re looking for more, I recommend checking out the Python list comprehension tutorial on DataCamp.