Nested list comprehension helps you create lists inside lists quickly and clearly. It saves time and makes your code shorter.
Nested list comprehension in 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.
matrix = [[1, 2], [3, 4]] squared = [[item**2 for item in row] for row in matrix] print(squared)
matrix = [] result = [[item*2 for item in row] for row in matrix] print(result)
matrix = [[5]] doubled = [[item*2 for item in row] for row in matrix] print(doubled)
matrix = [[1, 2, 3], [4, 5, 6]] filtered = [[item for item in row if item % 2 == 0] for row in matrix] print(filtered)
This program shows how to double every number in a nested list using nested list comprehension.
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)
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.
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.