A Visual Introduction to List Comprehensions in Python

Just show me the code! Quick link: Jupyter Notebook on GitHub

Why 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 cashier
cashier = []    
for item in cart:
    cashier.append(item)
print(cashier)
# The output is the same as the cart
Output: [3, 4, 12, 17, 19, 21, 23, 26, 30]

What happened here?

  1. We created a list of items in the cart

  2. We created an empty cashier list (the cashier didn’t have any of our items yet)

  3. We used a for loop to iterate over each item in our cart

  4. For each item we added it to the cashier list with .append()

  5. 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 comprehension
cashier_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.

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

  1. 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.

  2. 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.

  3. 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() statement

We 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 cart
cart = [5, 7, 9, 10, 12, 15, 19, 20, 22]
# Only give cashier_3 even numbers
cashier_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 numbers
Output: [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 above
Output: [10, 12, 20, 22]

What’s happening here?

Example of a non-list comprehension and a list comprehension with a conditional.

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.

  1. cashier_3 is created in blue.

  2. cart is being iterated over in green. item is being created as the for loop runs.

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

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


Over 100 and odd

cashier_4 only accepts numbers over 100 and are odd. How could you do this?

# Reminder of what cart looks like
cart = [5, 7, 9, 10, 12, 15, 19, 20, 22]
# Non-list comprehension for cashier_4
cashier_4 = []Now with a list comprehension.
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 100
Output: [105, 107, 109, 115, 119]

Now with a list comprehension

# List comprehension for cashier_4
cashier_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.

All the code in this article is available on GitHub and a video version of this article is available on YouTube.


Have advice for the next article? Feel free to leave a response or reach out via Twitter, LinkedIn, Email.