Nested List Comprehensions in Python - GeeksforGeeks (2024)

List Comprehension are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

Nested List Comprehension in Python Syntax

Below is the syntax of nested list comprehension:

Syntax: new_list = [[expression for item in list] for item in list]

Parameters:

  • Expression: Expression that is used to modify each item in the statement
  • Item:The element in the iterable
  • List: An iterable object

Python Nested List Comprehensions Examples

Below are some examples of nested list comprehension:

Example 1: Creating a Matrix

In this example, we will compare how we can create a matrix when we are creating it with

Without List Comprehension

In this example, a 5×5 matrix is created using a nested loop structure. An outer loop iterates five times, appending empty sublists to the matrix, while an inner loop populates each sublist with values ranging from 0 to 4, resulting in a matrix with consecutive integer values.

Python3

matrix = []

for i in range(5):

# Append an empty sublist inside the list

matrix.append([])

for j in range(5):

matrix[i].append(j)

print(matrix)

Output

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Using List Comprehension

The same output can be achieved using nested list comprehension in just one line. In this example, a 5×5 matrix is generated using a nested list comprehension. The outer comprehension iterates five times, representing the rows, while the inner comprehension populates each row with values ranging from 0 to 4, resulting in a matrix with consecutive integer values.

Python3

# Nested list comprehension

matrix = [[j for j in range(5)] for i in range(5)]

print(matrix)

Output

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Example 2: Filtering a Nested List Using List Comprehension

Here, we will see how we can filter a list with and without using list comprehension.

Without Using List Comprehension

In this example, a nested loop traverses a 2D matrix, extracting odd numbers from Python list within list and appending them to the list odd_numbers. The resulting list contains all odd elements from the matrix.

Python3

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

odd_numbers = []

for row in matrix:

for element in row:

if element % 2 != 0:

odd_numbers.append(element)

print(odd_numbers)

Output

[1, 3, 5, 7, 9]

Using List Comprehension

In this example, a list comprehension is used to succinctly generate the list odd_numbers by iterating through the elements of a 2D matrix. Only odd elements are included in the resulting list, providing a concise and readable alternative to the equivalent nested loop structure.

Python3

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

odd_numbers = [

element for row in matrix for element in row if element % 2 != 0]

print(odd_numbers)

Output

[1, 3, 5, 7, 9]

Example 3: Flattening Nested Sub-Lists

Without List Comprehension

In this example, a 2D list named matrix with varying sublist lengths is flattened using nested loops. The elements from each sublist are sequentially appended to the list flatten_matrix, resulting in a flattened representation of the original matrix.

Python3

# 2-D List

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

flatten_matrix = []

for sublist in matrix:

for val in sublist:

flatten_matrix.append(val)

print(flatten_matrix)

Output

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

With List Comprehension

Again this can be done using nested list comprehension which has been shown below. In this example, a 2D list named matrix with varying sublist lengths is flattened using nested list comprehension. The expression [val for sublist in matrix for val in sublist] succinctly generates a flattened list by sequentially including each element from the sublists.

Python3

# 2-D List

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

# Nested List Comprehension to flatten a given 2-D matrix

flatten_matrix = [val for sublist in matrix for val in sublist]

print(flatten_matrix)

Output

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

Example 4: Manipulate String Using List Comprehension

Without List Comprehension

In this example, a 2D list named matrix containing strings is modified using nested loops. The inner loop capitalizes the first letter of each fruit, and the outer loop constructs a new 2D list, modified_matrix, with the capitalized fruits, resulting in a matrix of strings with initial capital letters.

Python3

matrix = [["apple", "banana", "cherry"],

["date", "fig", "grape"],

["kiwi", "lemon", "mango"]]

modified_matrix = []

for row in matrix:

modified_row = []

for fruit in row:

modified_row.append(fruit.capitalize())

modified_matrix.append(modified_row)

print(modified_matrix)

Output

[['Apple', 'Banana', 'Cherry'], ['Date', 'Fig', 'Grape'], ['Kiwi', 'Lemon', 'Mango']]

With List Comprehension

In this example, a 2D list named matrix containing strings is transformed using nested list comprehension. The expression [[fruit.capitalize() for fruit in row] for row in matrix] efficiently generates a modified matrix where the first letter of each fruit is capitalized, resulting in a new matrix of strings with initial capital letters.

Python3

matrix = [["apple", "banana", "cherry"],

["date", "fig", "grape"],

["kiwi", "lemon", "mango"]]

modified_matrix = [[fruit.capitalize() for fruit in row] for row in matrix]

print(modified_matrix)

Output

[['Apple', 'Banana', 'Cherry'], ['Date', 'Fig', 'Grape'], ['Kiwi', 'Lemon', 'Mango']]


R

rituraj_jain

Improve

Previous Article

Reversing a List in Python

Next Article

Python | Test for nested list

Please Login to comment...

Nested List Comprehensions in Python - GeeksforGeeks (2024)

FAQs

Can you do nested list comprehension in Python? ›

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.

How to solve nested list in Python? ›

We can use either the append function or the insert function to add items to a nested list. The element or list is appended to the end of the list by the append() function, which accepts it as a parameter.

Are list comprehensions faster than for loops? ›

Time Saved with List Comprehension. Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations. Below, the same operation is performed by list comprehension and by for loop.

Is Python list comprehension lazy? ›

There's no lazy evaluation of lists in Python. List comprehensions simply create a new list. If you want "lazy" evaluation, use a generator expression instead.

Is it possible to have multiple if-else statements nested inside a list comprehension? ›

Avoid Complex Nesting: While it's possible to nest multiple if-else statements in list comprehension, excessive nesting can make the code harder to read and understand. Consider refactoring nested if-else statements into separate functions or using alternative control flow structures when the logic becomes too complex.

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.

What is the time complexity of nested list in Python? ›

Time complexity: O(n), where n is the number of elements in the list.

What is the difference between list and nested list in Python? ›

As we know, that list can contain any object, so here the concept of nested list is introduced. So simply, when there is a list containing a list inside itself as an element(sublist) or data, then that list is known as a nested list.

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.

When not to use list comprehensions? ›

Now let's take three examples to understand why you shouldn't be using list comprehensions for tasks that require super complex expressions. Because in such cases, list comprehensions—instead of making your code elegant—make your code difficult to read and maintain.

What is a faster alternative to list comprehension? ›

Array Computations are Faster than For Loops

apply() in pandas. Instead, you should always prefer array computations. It only took 4.84 seconds! This is 40% less time-intensive than our previous list comprehension (8.2 seconds).

What is faster map or list comprehension Python? ›

Comparing Execution Time

Without lambda: Map is faster than List Comprehension when function is already defined in case of map function. Example code 1: This code will print the time taken to evaluate numbers from 1 to 50. Map function is used without lambda.

Is list comprehension good practice? ›

Deciding When Not to Use a List Comprehension. List comprehensions are useful and can help you write elegant code that's easy to read and debug, but they're not the right choice for all circ*mstances. They might make your code run more slowly or use more memory.

What are the 4 types of comprehension in Python? ›

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

Can you break a list comprehension Python? ›

Conclusion. Python list comprehensions are a powerful tool for creating concise and readable code. While they do not have a direct 'break' statement, these methods allow you to achieve similar functionality within list comprehensions.

Can list comprehension be used for nested loops? ›

List Comprehension are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

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.

How do you concatenate lists in Python comprehension? ›

Python List Comprehension is an alternative method to concatenate two lists in Python. List Comprehension is basically the process of building/generating a list of elements based on an existing list. It uses for loop to process and traverses the list in an element-wise fashion.

How do you use two list comprehension in Python? ›

Below are some of the ways by which we can use list comprehension with multiple lists in Python:
  1. Using Conditional Statement.
  2. Using Nested Loops.
  3. Using Custom Function.
  4. Using Enumerate() Function.
Mar 1, 2024

Top Articles
Latest Posts
Article information

Author: Horacio Brakus JD

Last Updated:

Views: 5786

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Horacio Brakus JD

Birthday: 1999-08-21

Address: Apt. 524 43384 Minnie Prairie, South Edda, MA 62804

Phone: +5931039998219

Job: Sales Strategist

Hobby: Sculling, Kitesurfing, Orienteering, Painting, Computer programming, Creative writing, Scuba diving

Introduction: My name is Horacio Brakus JD, I am a lively, splendid, jolly, vivacious, vast, cheerful, agreeable person who loves writing and wants to share my knowledge and understanding with you.