List Comprehensions In Python


Getting Started

In my pursuit of Python wizardry, I'd like to share with you one of Python's cool features: list comprehensions. List comprehensions provide a clean one line code solution that will work for many use cases. Today, I will cover four different examples of how you could use them.

Squaring Every Number In A List

Let's say we have a list of numbers, and we want to square each number in the list. If we wanted to do things in an old fashioned manner, we could do the following:

def square(list):
  squares = []

  for num in list:
    squares.append(num ** 2)

  return squares

With a list comprehension, we can cut out all those lines of code into a one line solution.

def square(list):
  return [num ** 2 for num in list]

Nested Loops

Nested loops are usually not very fun to work with. With a list comprehension, you can do it all in one line.

ice_creams = ['vanilla', 'chocolate', 'mint']
types = ['sundae', 'cone', 'frappe']
combined = [ice_cream + ' ' + type for ice_cream in ice_creams for type in types]

# ['vanilla sundae', 'vanilla cone', 'vanilla frappe', 'chocolate sundae', 'chocolate cone', 'chocolate frappe', 'mint sundae', 'mint cone', 'mint frappe']

Reading from left to right, for_ice_cream in ice_creams will be the outer loop, and for type in types will be the inner.


You can use a list comprehension to filter out items as well. Let's eliminate any ice cream flavors from our list that are four characters in length or less.

ice_creams = ['vanilla', 'chocolate', 'rocky road', 'mint', 'raspberry']
new_ice_creams = [ice_cream for ice_cream in ice_creams if len(ice_cream) > 4]

# ['vanilla', 'chocolate', 'rocky road', 'raspberry']

While cool, Python does have it's own built in filter function. Using the filter function returns what's called an "iterator", not a list. You actually have to go through one more step and convert that iterator back into a list, which is annoying.

ice_creams = ['vanilla', 'chocolate', 'rocky road', 'mint', 'raspberry']
new_ice_creams = filter(lambda ice_cream: len(ice_cream) > 4, ice_creams)

# ['vanilla', 'chocolate', 'rocky road', 'raspberry']

Conditionals On The Value

If we wanted to iterate through a list and find out which numbers are "big" or "small", we could use the following list comprehension:

values = [1, 50, 15, 22, 75, 4]
small_big = ['small' if num < 25 else 'large' for num in values]

# ['small', 'large', 'small', 'small', 'large', 'small']


That's it for my Python list comprehension's overview! If you have any problems understanding any of this, feel free to shoot me a message, and I'll make sure it's crystal clear.