0
0
Pythonprogramming~5 mins

Nested list comprehension in Python

Choose your learning style9 modes available
Introduction

Nested list comprehension helps you create lists inside lists quickly and clearly. It saves time and makes your code shorter.

When you want to create a table or grid of values, like a chessboard or multiplication table.
When you need to flatten a list of lists into a single list.
When you want to apply a function to every item in a list of lists.
When you want to filter items inside nested lists based on a condition.
Syntax
Python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_matrix = [[expression for item in inner_list] for inner_list in matrix]

The outer loop goes last in the syntax but runs first in logic.

You can add conditions inside either the inner or outer loop.

Examples
This squares each number inside the nested lists.
Python
matrix = [[1, 2], [3, 4]]
squared = [[item**2 for item in row] for row in matrix]
print(squared)
Handles empty outer list, result is also empty.
Python
matrix = []
result = [[item*2 for item in row] for row in matrix]
print(result)
Works with a single element nested list.
Python
matrix = [[5]]
doubled = [[item*2 for item in row] for row in matrix]
print(doubled)
Filters only even numbers inside each nested list.
Python
matrix = [[1, 2, 3], [4, 5, 6]]
filtered = [[item for item in row if item % 2 == 0] for row in matrix]
print(filtered)
Sample Program

This program shows how to double every number in a nested list using nested list comprehension.

Python
def print_matrix(matrix):
    for row in matrix:
        print(row)

original_matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original matrix:")
print_matrix(original_matrix)

# Create a new matrix with each number doubled
new_matrix = [[item * 2 for item in row] for row in original_matrix]
print("\nNew matrix with doubled values:")
print_matrix(new_matrix)
OutputSuccess
Important Notes

Time complexity is O(n*m) where n is number of inner lists and m is number of items in each.

Space complexity is also O(n*m) because a new list is created.

Common mistake: mixing up the order of loops or forgetting to nest the inner loop inside the outer one.

Use nested list comprehension when you want concise code for nested loops; use regular loops if you need more complex logic or debugging.

Summary

Nested list comprehension lets you create or transform lists inside lists in one line.

It is useful for working with tables, grids, or any nested data.

Remember the outer loop goes last in the syntax but runs first in logic.