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

Nested List Comprehensions in Python - GeeksforGeeks? ›

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.

What is nested list comprehension in Python? ›

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).

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.

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.

What are list comprehensions in Python? ›

List comprehension is an easy to read, compact, and elegant way of creating a list from any existing iterable object. Basically, it's a simpler way to create a new list from the values in a list you already have. It is generally a single line of code enclosed in square brackets.

What is the purpose of nested list? ›

A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if we want to create a matrix or need to store a sublist along with other data types.

What are the advantages of using list comprehensions? ›

List comprehensions are optimized for performance. They are faster and use less memory compared to traditional for loops, making them an efficient choice for iterating over and transforming data.

Why is it called list comprehension Python? ›

In a list or set comprehension, instead of giving the elements of the list or set explicitly, the programmer is describing what they comprehend (in the "include" sense) with an expression. Because it's a very comprehensive way to describe a sequence (a set in math and other languages, and a list/sequence in Python).

What are the 2 main types of comprehension? ›

Literal comprehension is often referred to as 'on the page' or 'right there' comprehension. This is the simplest form of comprehension. Inferential comprehension requires the reader/viewer to draw on their prior knowledge of a topic and identify relevant text clues (words, images, sounds) to make an inference.

What is the difference between list comprehension in Python? ›

The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code. List comprehension requires less computation power than a for loop because it takes up less space and code.

How to check if a list is 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 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 you code a nested list? ›

Utilize the <li> tag to list individual items within the <ul> tag. The <ul> tag serves as the parent container for <li> tags, establishing the structure of the list. Nested lists can be created by placing additional <ul> or <ol> tags within <li> tags, enabling the creation of hierarchical structures.

Is list comprehension good or bad in Python? ›

Well, the performance of list comprehension is still a little bit better than the for-loop one. However, I have to say that the list comprehension starts to have much worse readability because of the complex conditions.

Is Python list comprehension faster? ›

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.

What is mean using list comprehension in Python? ›

A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.

What is nested statement in Python? ›

Nested if statements are if statements inside another if statement. These can be very useful to make complex decisions in your script. They can be several levels deep. Its better to avoid deep nesting as it may get confusing to read such deeply nested if statements.

What is nested method in Python? ›

Nested (or inner, nested) functions are functions that we define inside other functions to directly access the variables and names defined in the enclosing function. Nested functions have many uses, primarily for creating closures and decorators.

What is nested data in Python? ›

Nested data structures are data structures that contain other data structures. In Python, this means that a data structure can contain lists, dictionaries, tuples, and other objects. Nested data structures are useful for organizing complex information in a way that is easy to access and manipulate.

Top Articles
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated:

Views: 6131

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.