VOOZH about

URL: https://www.geeksforgeeks.org/python/nested-list-comprehensions-in-python/

⇱ Nested List Comprehensions in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Nested List Comprehensions in Python

Last Updated : 5 Jul, 2025

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.

Syntax of Nested List Comprehension

new_list = [[expr for item in inner_iterable] for item in outer_iterable]

Parameters:

  • expr: The expression to compute or transform each item.
  • inner_iterable: The iterable used for the inner list.
  • outer_iterable: The iterable used for the outer list.

Let's look at some of the examples:

Example 1: Creating a Matrix

Without List Comprehension


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]]

Explanation: This code builds a 5x5 matrix (list of lists), where each row contains numbers from 0 to 4 using nested loops.

Using List Comprehension


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]]

Explanation: A more concise version of the same logic, the inner loop [c for c in range(5)] creates each row and the outer loop repeats it 5 times.

Example 2: Filtering a Nested List Using List Comprehension

Without List Comprehension


Output
[1, 3, 5, 7, 9]

Explanation: This loops through a 2D list and adds all odd numbers to a new list odds.

Using List Comprehension


Output
[1, 3, 5, 7, 9]

Explanation: This single line does the same thing, it goes through each row 'r', each element 'e' and includes 'e' only if it's odd.

Example 3: Flattening Nested Sub-Lists

Without List Comprehension


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

Explanation: This code flattens a nested list m by iterating over each sublist and adding every value to flat.

With List Comprehension


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

Explanation: A more compact version that loops through every sublist r and each value v and collects all values into a flat list.

Example 4: Manipulate String Using List Comprehension

Without List Comprehension


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

Explanation: Each string (fruit name) in the nested list is capitalized using nested loops.

With List Comprehension


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

Explanation: Each fruit f in every row r is capitalized using .capitalize() and the modified rows are collected into mod_m.

Comment