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)

References

Top Articles
As antisemitism grows, it is easier to condemn than define : Consider This from NPR
We tried 10 dim sum restaurants. The best is in Malden. - The Boston Globe
Menards Thermal Fuse
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
Myexperience Login Northwell
How do you mix essential oils with carrier oils?
Sotyktu Pronounce
Zendaya Boob Job
Olivia Ponton On Pride, Her Collection With AE & Accidentally Coming Out On TikTok
ATV Blue Book - Values & Used Prices
The Binding of Isaac
Mephisto Summoners War
Evil Dead Rise Showtimes Near Regal Columbiana Grande
Otterbrook Goldens
Kvta Ventura News
Gino Jennings Live Stream Today
The Exorcist: Believer (2023) Showtimes
R Personalfinance
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Toothio Login
Strange World Showtimes Near Savoy 16
Roanoke Skipthegames Com
What Is a Yurt Tent?
Is Poke Healthy? Benefits, Risks, and Tips
Where to eat: the 50 best restaurants in Freiburg im Breisgau
Busch Gardens Wait Times
Helpers Needed At Once Bug Fables
Die wichtigsten E-Nummern
What Is Opm1 Treas 310 Deposit
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Human Unitec International Inc (HMNU) Stock Price History Chart & Technical Analysis Graph - TipRanks.com
Greencastle Railcam
Trebuchet Gizmo Answer Key
Frostbite Blaster
Exploring The Whimsical World Of JellybeansBrains Only
Federal Student Aid
Top-ranked Wisconsin beats Marquette in front of record volleyball crowd at Fiserv Forum. What we learned.
Bitchinbubba Face
Robeson County Mugshots 2022
M Life Insider
Gopher Hockey Forum
Torrid Rn Number Lookup
How to Connect Jabra Earbuds to an iPhone | Decortweaks
877-552-2666
Learn4Good Job Posting
40X100 Barndominium Floor Plans With Shop
El Patron Menu Bardstown Ky
Runescape Death Guard
Metra Union Pacific West Schedule
Att Corporate Store Location
Island Vibes Cafe Exeter Nh
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6320

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.