List Comprehensions in Python (Complete Guide with Examples)

  • by
Python List Comprehensions Cover Image
  • Save

In this post, we’ll cover everything you need to know about List Comprehensions in Python, using comprehensive examples! List comprehensions provide elegant, concise ways to create, modify, and filter lists in Python.

Video Tutorial on Python List Comprehensions

Table of Contents

What is a List Comprehension in Python?

A list comprehension is an elegant, concise way to define and create a list in Python. The code is written in a much easier-to-read format. Python List Comprehensions consist of square brackets containing an expression, which is executed for each element in an iterable. Each element can be conditionally included and or transformed by the comprehension.

What is a List in Python?

A Python list a built-in data structure and a compound data type, meaning you can use it to group values together. Lists are heterogeneous, meaning they can have a combination of different data types, such as Booleans, strings, integers, etc.

What makes Python lists different from other Python compound data types (e.g., dictionaries, tuples), in that it’s an ordered collection (meaning items have an index) and they are mutable (meaning they can be changed).

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Why Use List Comprehensions in Python?

List comprehensions provide concise ways to create lists. One main use is to make lists where each element is the result of an operation applied to each item of an iterable item, or to create a smaller set of items of a given list.

List Comprehension Benefits

Python list comprehensions are a more Pythonic way to create, modify, and filter lists.

This is incredibly helpful because it represents a single tool to complete a number of tasks, rather than relying on for loops, map() functions, or filter() functions. This is great as you can apply one method, rather trying to fit a use case to a scenario.

List comprehensions are also, in many cases, easier to read than for-loops. They don’t require you to instantiate an empty list or to append items to a new list.

How Do You Write a List Comprehension?

List comprehensions in Python follow the structure of: [Expression for Item in Iterable].

  • An expression can be any expression – a single item, a function applied to an item, etc.
  • An item is an item in an iterable,
  • An iterable is an object that you can iterate over (such as a list, tuple, etc.)
Python List Comprehensions Syntax
  • Save
The syntax of a Python list comprehension

Let’s see what this looks like with an example:

Python List Comprehension Example
  • Save

In the above example, we iterate over a list that contains the numbers 1-5 and square each number. If we wrote this out as Python code, it would look like this:

squares = [x ** 2 for x in [1,2,3,4,5]
print(squares)

#Returns [1,4,9,16,25]

List Comprehension vs. For Loop

List comprehensions have concise terminology for replacing for-loops that are used to iterate over items.

For Loops can be used in Python to create lists. However, they are slower to write and to execute.

Want to learn more about For Loops? Check out our complete guide to for loops!

Let’s take a look at an example of a for loop. Below, we use a for-loop to create a list of 0 to 9. To do this, we’ll:

  1. Instantiate (create) an empty list,
  2. Loop of items in a range of elements, and
  3. Append each item to the end of the list.
numbers = []
for i in range(10):
	numbers.append(i)
print(numbers)

To do this using a list comprehension, we can simply write the code below:

numbers = [i for i in range(10)]
print(numbers) 

Both of these pieces of code return:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

It’s important to note that every list comprehension can be written as a for loop, but not every for-loop can be a list comprehension. Always strive for readability!

Why are List Comprehensions Faster than For-Loops?

List comprehensions are faster than for loops because they are optimized to be interpreted a predictable pattern, do not need to look up the list each time, and do not need to execute the append statement during each run.

List Comprehensions vs. Lambda and Map() Functions

Lambda functions are anonymous functions in Python, meaning that they are used only when they are created. These functions are generally used with the map() function, especially in a way to alter lists.

Let’s explore how a map and lambda functions can be used to alter a list. In the example, we’ll change a list of weight in kilograms to pounds:

weights_kg = [1.0, 3.5, 4.2]
weights_lbs = list(map(lambda x:float(2.2) * x, weights_kg))
print(weights_lbs)

To write this as a list comprehension, we could write the following code:

weights_kg = [1.0, 3.5, 4.2]
weights_lbs = [x * 2.2 for x in weights_kg]
print(weights_lbs)

Both of these returns the following:

[2.2, 7.7, 9.24]

Python List Comprehension If Else (Conditionals)

Conditionals can enhance Python list comprehensions significantly. They serve two main purposes:

  1. To filter a list, and
  2. To modify items in a list.

Depending on what you want to use a Python list comprehension if else statement for, the conditional goes into a difference place.

Modifying a List with a List Comprehension If Else Statement

If you want to modify items in a list based on a condition, the conditional goes in the front of the list comprehension:

new_list = [expression (if-else statement) for item in iterable]

Let’s try this with an example. We’ll take a list with numbers from 1-5 and label items as either even or odd:

old_list = [1,2,3,4,5]
new_list = ['even' if x % 2 == 0 else 'odd' for x in old_list]
print(new_list)

For each item in the list, Python evaluates the modulus of a number and 2 – if the value returned is 0, the string ‘even’ is added to the new list. If it not 0, ‘odd’ is added to the new list.

This returns the following:

['odd', 'even', 'odd', 'even', 'odd']

Filtering a List with List Comprehension If Statement

If you want to filter a list, the conditional goes to the end of the list comprehension:

new_list = [expression for item in iterable (if statement)]

Let’s try this with another example. If we had a list of numbers from 1-5 and wanted to filter out any even numbers, we could write:

old_list = [1,2,3,4,5]
new_list = [x for x in old_list if x % 2 == 1]
print(new_list)

For each item in the list, Python evaluates the modulus of the item and 2, and if the value returned is 1, then the original item is added to the new list.

This returns the following:

[1, 3, 5]

Multiple If Conditions in List Comprehensions

Multiple if conditions can be applied within Python List Comprehensions by chaining them together.

Let’s take a look at an example. If we wanted to generate a list of numbers that are divisible by 2 and by 5, we could do this with a for-loop:

new_list = []
for i in range(1, 101):
    if i % 2 == 0:
        if i % 5 == 0:
            new_list.append(i)
print(new_list)

To do this with a list comprehension, we can cut down the amount of code significantly:

new_list = [i for i in range(1, 101) if i % 2 == 0 if i % 5 == 0]
print(new_list)

This returns the following:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Nested List Comprehensions

List Comprehensions can also be nested, which is especially useful when working with lists of lists. This can include generating lists of lists, reducing them to normal lists, or transposing them.

For example, if we had a list of list that looked like the list below:

nested_list = [[1,2,3],[4,5,6],[7,8,9]]

If we wanted to reduce this to a flattened list, we could do this with a for-loop:

nested_list = [[1,2,3],[4,5,6],[7,8,9]]
flat_list = []
for list in nested_list:
	for item in list:
		flat_list.append(item)
print(flat_list)

To do this with a list comprehension, we can write:

nested_list = [[1,2,3],[4,5,6],[7,8,9]]
flat_list = [i for j in nested_list for i in j]
print(flat_list)

Both of these return:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Example: Finding Common Items in Two Lists Using List Comprehensions

We can use nested list comprehensions to identify common items between two lists.

Let’s first see how this can be done using for-loops:

list1 = ['apple', 'orange', 'banana', 'grape']
list2 = ['grapefruit', 'apple', 'grape', 'pear']
common_items = []

for i in list1:
	for j in list2:
		if i == j:
			common_items.append(j)
print(common_items)

To do this using a list comprehension, we can simply write:

list1 = ['apple', 'orange', 'banana', 'grape']
list2 = ['grapefruit', 'apple', 'grape', 'pear']

common_items = [i for i in list1 if i in list2]
print(common_items)

Both of these return the same list, but the list comprehension is much easier to understand!

['apple', 'grape']

When Not to Use List Comprehensions

List Comprehensions are great because they are Pythonic – until they’re not. Python strives for readability (see The Zen of Python). While in most cases, list comprehensions tend to be more readable than other methods such as for-loops, they can also become quite complex. In these cases, it may be better to use another method to help future readability.

It’s important to note that every list comprehension can be written as a for loop, but not every for-loop can be a list comprehension. Always strive for readability!

It’s important to not write incredibly long list comprehensions to replace simple for-loops.

Check out some other Python tutorials on datagy, including how to write functions in Python and how to create a VLOOKUP in Python!

Conclusion: Python List Comprehensions

In this post, we learned how to use Python list comprehensions to create, modify, and filters lists. Specifically, we learned:

  • The benefits of list comprehensions,
  • How to use list comprehensions to replace for-loops and map() functions,
  • How to add conditionals to list comprehensions,
  • How to use nested list comprehensions, and importantly,
  • When not to use list comprehensions.

Thanks for reading! If you found this tutorial helpful, check out some of our other Python tutorials, including an in-depth look at dictionary comprehensions.

Cover of Introduction to Python for Data Science
  • Save

Want to learn Python for Data Science? Check out my ebook for as little as $10!