However, you might get worked up if you don’t know how to use it. It can even be more frustrating if you don’t know where to apply it in your code. Here, we’ll show you how to use list comprehension in Python with some real-life examples.

What Is List Comprehension in Python and How Does It Work?

Creating a list of items with Python is easy. However, the task can become a bit tedious when you need to generate a list of values or items from mathematical or string operations. That’s when using list comprehension can come in handy.

An advantage of using list comprehension is that you can perform several operations in a single list.

In contrast, it creates new items and appends them to an empty list it declares automatically. So instead of making an empty list manually and appending to it with a for loop, Python’s list comprehension lets you do this automatically without you bothering about how the new list comes through.

The term “list comprehension” comes from the fact that all operations are in a Python list assigned to a named variable. As we stated earlier, it lets you perform specific operations in a single line of code. It then appends the output to a new list.

Ultimately, you can also use the output of a list comprehension for other purposes. That’s because it stacks expressions in separate variables. So you can refer to them later.

For instance, you might be scraping a website with BeautifulSoup. Assume you intend to get the name of all items and their prices from the website.

You then decide to put the scraped data in a CSV or an Excel file. The ideal practice is to scrape the name of all items and their prices and place both of them in separate columns. However, using a list comprehension, in that case, ensures that you have the scraped data in dedicated variables. You can then convert such variables into a Python DataFrame later.

Look at the example below:

Once you get the looped variables, you can then put them in separate columns in a DataFrame using Python’s Pandas.

How to Create and Use a List Comprehension in Python

The for loop is an essential iterator in a list comprehension. Generally, a list comprehension in Python takes this format:

Printing ComprehensionVariable outputs the result of the above code as a list.

However, be careful not to confuse a list comprehension with an open for loop.

For example, let’s use an open for loop to get a list of all multiples of three between 1 and 30:

To compare the two, let’s do the same thing using a list comprehension:

You can use a list comprehension with conditional statements as well. The example code below prints all odd numbers between 1 and 10:

Now, let’s also rewrite the code above using an open for loop:

A list comprehension also accepts nested if statements:

It also takes a nested for loop:

You can also have a plain nested for loop in a list comprehension:

You can manipulate strings with Python list comprehension as well. Let’s have a look at a word counter comprehension below:

A list comprehension can also accept a function that performs a specific operation. Let’s insert a multiplier function that gets even numbers in a list comprehension to see how this works:

You can still write the code above in a single function without using comprehension. But a list comprehension is useful when you need to perform several iterations and place each of them in separate variables.

For instance, you can perform another operation on n and have a dedicated variable for it. Let’s modify the comprehension above to generate even numbers from odd ones:

Dictionary and Set Comprehensions

In addition to a list comprehension, Python also offers a dictionary and a set comprehension functionality.

Have a look at the example dictionary comprehension below to see how it works:

The code above iterates through the list of numbers between 1 and 9 and makes them the keys. It then tells Python to multiply each key by two. Finally, it presents the results of that operation as the corresponding values for each key in the resulting array.

A set comprehension is a bit similar to a list comprehension. Here’s an example of a set comprehension:

However, unlike list comprehension, set comprehension removes duplicates:

You can try out the code above using a list comprehension to see how they differ.

Can You Use List Comprehension Every Time?

We’ve taken a look at different examples of list comprehension and where you can use them. However, like any other Python method, the use-case of a list comprehension depends on the specific problem you wish to solve. Therefore you should only use it if it’s ideal for the specific problem you wish to solve.

One of the purposes of list comprehension is to simplify your code and make it more readable. So, make sure you avoid complexity when dealing with it. For instance, a long Python comprehension can become complex to read. That defeats its purpose.