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? ›

The nested list is created by moving over each element in the original list using list comprehension. Each element k is enclosed in a list [k], thus creating a nested list with each element as a separate sublist. We can also create nested sublists of a specific size (e.g., creating sublists of size 3 or 2).

What are list comprehensions in Python? ›

What is list comprehension in Python? A concise syntax for creating a list from a range or an iterable object by applying a specified operation on each of its items. It performs much faster than its alternatives, such as for loops, lambda functions, conditionals, etc.

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.

Is list comprehension faster than for loop? ›

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.

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 set comprehension and list comprehension in Python? ›

Set comprehension is a method for creating sets in python using the elements from other iterables like lists, sets, or tuples. Just like we use list comprehension to create lists, we can use set comprehension instead of for loop to create a new set and add elements to it.

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

A list within another list is referred to as a nested list in Python. We can also say that a list that has other lists as its elements is a nested list. When we want to keep several sets of connected data in a single list, this can be helpful.

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

Python Test Nested List Using type() method. In this example, the Python code determines if the list test_list contains any nested lists by iterating through its elements and setting the variable res to True if a nested list is found. The final output indicates whether the original list contains a nested list or not.

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

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.

Why use list comprehensions? ›

Python list comprehensions allow you to express complex operations on lists in a single line of code. This concise syntax enhances code readability and makes it easier for developers to understand and maintain.

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.

How to get rid of duplicates in a list in Python? ›

To remove duplicates from a list in Python, iterate through the elements of the list and store the first occurrence of an element in a temporary list while ignoring any other occurrences of that element. The basic approach is implemented in the naive method by: Using a For-loop to traverse the list.

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 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 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 data in Python? ›

Now that we have a basic understanding of tuples and lists, let's explore how to create nested structures using these data types. A nested structure simply means that you can have tuples and lists within other tuples and lists. This allows you to represent hierarchical and complex data.

References

Top Articles
Legale wietfabriek in Nieuw Beerta in de steigers. Eerste cannabisplantjes komen in juni. 'We gaan geschiedenis maken' - De tevreden rookster
Download Fae Farm NSP, XCI ROM + v2.0.1 Update - Egg NS Emulator
Www.craigslist Virginia
Danatar Gym
Blackstone Launchpad Ucf
Lost Ark Thar Rapport Unlock
Nwi Police Blotter
Magic Mike's Last Dance Showtimes Near Marcus Cedar Creek Cinema
Weather In Moon Township 10 Days
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Natureza e Qualidade de Produtos - Gestão da Qualidade
Fire Rescue 1 Login
Ladyva Is She Married
Nonuclub
7440 Dean Martin Dr Suite 204 Directions
Kaomoji Border
How pharmacies can help
97226 Zip Code
12 Top-Rated Things to Do in Muskegon, MI
Soulstone Survivors Igg
Www.dunkinbaskinrunsonyou.con
Glover Park Community Garden
Engineering Beauties Chapter 1
Ceramic tiles vs vitrified tiles: Which one should you choose? - Building And Interiors
Rapv Springfield Ma
Mythical Escapee Of Crete
Pokemon Inflamed Red Cheats
Tottenham Blog Aggregator
CohhCarnage - Twitch Streamer Profile & Bio - TopTwitchStreamers
Federal Express Drop Off Center Near Me
Duke Energy Anderson Operations Center
Ravens 24X7 Forum
Roadtoutopiasweepstakes.con
Goodwill Thrift Store & Donation Center Marietta Photos
Car Crash On 5 Freeway Today
Google Jobs Denver
AI-Powered Free Online Flashcards for Studying | Kahoot!
Emerge Ortho Kronos
Heelyqutii
Pepsi Collaboration
Empires And Puzzles Dark Chest
888-333-4026
Rs3 Bis Perks
Tryst Houston Tx
Tsbarbiespanishxxl
Author's Purpose And Viewpoint In The Dark Game Part 3
8776725837
Nimbleaf Evolution
Sara Carter Fox News Photos
Gander Mountain Mastercard Login
Doelpuntenteller Robert Mühren eindigt op 38: "Afsluiten in stijl toch?"
Ciara Rose Scalia-Hirschman
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 6579

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.