How to Write Nested List Comprehensions in Python | Built In (2024)

When you’re learning of a new programming language, it’s challenging to figure out how to keep your code clear.

One of the best ways to make Python code more accessible to your colleagues comes from collapsing multiple lines of code into a single line. In a recent article I showed you how to do this using list comprehensions. This article builds off that one, so you should definitely check it out before continuing here.

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there’s no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.

Since this is such a powerful function, let’s take a deeper look.

What Are Nested List Comprehensions?

List comprehensions create a new list by scanning all items in a list, checking to see if they meet a condition, passing the values that do and applying a function to them. You can place one list comprehensions within another list comprehension. This creates a nested list comprehension and further simplifies your code.

Back to BasicsIncrease the Readability of Your Python Script With 1 Simple Tool

Quick Refresher: What Is a List Comprehension?

As a quick refresher, a list comprehension is a way to create a new list by filtering elements in a list that meet a condition, transforming the elements as desired and storing the new values in a list. All we need is a single line of code. The code is as follows:

Result = [Function for Value in DataSet if Condition]

That code sorts through each value in your data set, checks to see if it meets the condition, applies the stated function and stores it in a list named Result. It applies a for loop, if statement and a function all in a single line.

Here’s an example showing how list comprehensions work:

Numbers = [1,2,3,4,5,6,7,8,9,10]Result_ForLoop = []for Number in Numbers: if Number > sum(Numbers)/len(Numbers): Result.append(Number)Result_ListComprehension = []Result_ListComprehension = [Number for Number in Numbers if Number > sum(Numbers)/len(Numbers)]print(Result_ForLoop)print(Result_ListComprehension)

Those two print statements will show the exact same result: [6,7,8,9,10].

For a more detailed discussion of how those two pieces of code return the same result see my guide to list comprehensions.

Now let’s dive in to nested list comprehensions.

What Is a Nested List Comprehension?

A nested list comprehension doubles down on the concept of list comprehensions. It’s a way to combine not only one, but multiple for loops, if statements and functions into a single line of code. This becomes useful when you have a list of lists (instead of merely a single list).

Let’s consider an example. Say you have two lists of numbers and you want to return the square of all of the even numbers. You could write the following code using a single list comprehension:

Numbers = [[1,2,3,4,5,6,7,8,9,10], [11,12,13,14,15,16,17,18,19,20]]Result = []for list in Numbers: Squares = [Number ** 2 for Number in list if Number % 2 == 0] Result.extend(Squares)

The above code:

  • Creates the input data set and stores it in Numbers. The input data consists of two lists. The first list runs from one to 10, and the second list runs from 11 to 20.

  • Then the code creates an empty list called Result. We will use Result to store the output from our function.

  • The code will then create a for loop and iterate through each list in Number.

  • Within the for loop it uses a list comprehension to search through the provided list, check if each number in the list is divisible by two (i.e. Is it even?), squares the result and stores it in a list. This list is then stored in the variable Squares.

  • The final line then adds Squares to Result giving us a list of the squares of the values that are divisible by two.

Since there are two lists in Numbers it executes the for loop twice.

Now, since you’re familiar with list comprehensions you probably understand it’s fully possible to remove the for loop and if statement with a list comprehension. Doing so creates a nested list comprehension.

To do this we write a single list comprehension with two for loops. It’s key to remember three things when doing this:

  • The function is always the first term.

  • The for loops are always written in the order of the nesting.

  • The condition is always placed at the end.

So, to construct a nested for loop in our example we need to:

  • Write the function to square the numbers that have passed the filter.

  • Write a for loop iterating through all of the lists in Numbers.

  • Write a for loop iterating through each number in the passed list.

  • Write a condition passing the numbers that are even.

And we need to do it in that order. Fortunately, once we’ve created that structure in our minds it’s easy to do. The code appears as follows:

Result = [Number ** 2 for list in Numbers for Number in list if Number %2 == 0]

If you replace the previous code you’ll find this nested list comprehension returns the same result.

This is a powerful way to reduce several lines of code into a single line and can significantly increase the readability of your code. Since it’s in a single line, anybody who understands list comprehensions will be able to quickly deduce what is happening and follow your logic.

Learn More With Peter GrantNeed to Automate Your Data Analysis? Here’s How.

Before You Start Nesting...

While nested list comprehensions are a useful way to improve your code's readability, there is a downside. List comprehensions can get very complex very quickly. What if you have a hundred for loops? Or what if you have very complex function and condition descriptions?

I could envision a complex nested for loop spanning several lines of code, and becoming nearly impossible to read or understand. While there’s Python has no technical limit to understanding complex a nested for loops, there is a human limit.

If you have a complex piece of code with many for loops, or complex functions and conditions, using a nested for loop may actually make your code more difficult to understand. Take care to ensure your efforts are making your collaborators’ lives easier instead of harder.

Generally speaking, if you have more than three levels of nesting it may be easier for everybody if you just write out the for loops.

Learning to make code easy for other people to understand is a critical task in the modern workplace —especially as more and more teams work remotely. List comprehensions and nested list comprehensions are a useful Python tool to help your collaborators quickly understand how your code works.

How to Write Nested List Comprehensions in Python | Built In (2024)

FAQs

Can you do nested list comprehension in Python? ›

List comprehensions and nested list comprehensions are a useful Python tool to help your collaborators quickly understand how your code works.

How to solve nested list in Python? ›

Nested lists in Python can be modified using the same list operations as regular lists. This means you can add elements to nested lists using methods like append(), insert(), and extend(). To add a new element to the end of a nested list, you can use the append() method.

How do you combine two list comprehensions in Python? ›

Python's extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

How to make set comprehension in Python? ›

The syntax for set comprehension comprises two parts: a new set and an expression that defines the value of each element within the set. It can incorporate a variable that takes each value within the iterable object and a conditional statement that filters the elements.

Is list comprehension faster than for loop? ›

List comprehensions are often faster than loops because they use a more optimized internal mechanism for iterating over the collection. Additionally, list comprehensions allow you to perform transformations and filtering in a single statement, which can lead to more efficient code.

What is a nested list with an example? ›

A nested list is a list that appears as an element in another list. In this list, the element with index 3 is a nested list. If we print( nested[3] ), we get [10, 20] .

How do I get unique values from a nested list in Python? ›

Using the setdefault() Method for Nested Lists

When working with nested lists, the setdefault() method can be used to obtain unique values efficiently. It allows us to create a dictionary with the elements as keys and their occurrences as values.

How to extract elements from a nested list in Python? ›

You can also extract an element from the list you extracted. To do this, you use two indices. The first index is the position of the list, and the second index is the position of the element within the list.

How to check if something is in a nested list in Python? ›

Test for Nested List Using any() and instance() The combination of the above functions can be used to perform this task. The any() is used to check for each of the occurrences and the isinstance() is used to check for the list.

What are 3 different ways to combine 2 lists in Python? ›

Below, I will show you five different methods to combine two lists in Python: using the + operator or list comprehension to produce a new concatenated list; a for loop or extend() method to append elements of one list to the other; and using * operators to unpack elements into a combined list.

How do I combine two lists into a nested list in Python? ›

Using the extend() method

When you use extend() , it modifies the original list in-place, adding elements from the iterable to the end of the list. In this example, extend() is used on list1 to append all elements from list2 to it. After executing this code, list1 will contain the merged elements of both lists.

What is a list comprehension between two lists? ›

A list comprehension works by translating values from one list into another by placing a for statement inside a pair of brackets, formally called a generator expression. A generator is an iterable object, which yields a range of values.

How to write a comprehension in Python? ›

Three steps to write a comprehension:
  1. Write the outer square brackets. [ ]
  2. Write a regular foreach loop over the source list inside the brackets, [for n in nums]
  3. Finally write an expression for the new elements at the left, like n * n. [n * n for n in nums]

What are the four types of comprehensions in Python? ›

There are four types of comprehension in Python for different data types – list comprehension, dictionary comprehension, set comprehension, and generator comprehension.

What is the difference between set comprehension and list comprehension in Python? ›

The key aspect of set comprehension that makes it unique is that it returns a set, which means the elements inside will be unordered and cannot contain any duplicates. The rest is pretty much the same as a list comprehension. The input can be anything that contains a group of elements. Let's look at some examples.

Can set comprehension be used for nested loops? ›

As with list and dictionary comprehensions, you can nest one set comprehension within another, although there is one very important caveat. In general with Python, when it comes to sets inside sets, the inner sets have to be frozen sets, or you will get an error.

Can you do else in list comprehension Python? ›

List comprehension in Python is a way to make the elements get added to the list more easily. We can use if-else with List Comprehension which makes the code smaller and more modular instead of using long if-else conditions making it very unstructured.

Is it OK to have nested functions in Python? ›

Unless you need to hide your functions from the outside world, there's no specific reason for them to be nested. You could define those functions as private top-level functions, and you'd be good to go. In this section, you'll learn about closure factory functions.

Is tuple comprehension possible in Python? ›

I think the short answer is that tuples are immutable, which means that once created, they can't be changed. The comprehension apparently grows the structure, which means adding one item at a time — it's story of syntactic sugar for appending items in a for loop. You can't do that with tuples which are fixed.

Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6697

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.