Nested List Comprehension in Python

List comprehension is a concise way to create lists in Python. It allows you to generate a new list by applying an expression to each element of an iterable (like a list, tuple, or range) in a single line of code.

The syntax of list comprehension is:

[expression for item in iterable if condition]

Nested List comprehension refers to using a list comprehension within another list comprehension. This is useful when dealing with nested structures like a list of lists (matrices) or multi-dimensional arrays.

The syntax of nested list comprehension is:

[[expression for inner_item in inner_iterable] for outer_item in outer_iterable]

With optional conditions:

[[expression for inner_item in inner_iterable if inner_condition] for outer_item in outer_iterable if outer_condition]

Example 1: Create multiplication table

Let’s create a 2D list (table) where each element is the product of two numbers: the row index (i) and the column index (j).

table = [[i*j for j in range(1, 4)] for i in range(1,4)]
print(table) # Output: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

In the above code example:

(1) Outer list comprehension

[...for i in range(1,4)]

This iterates over i values from 1 to 3 (inclusive), creating a list for each row.

(2) Inner list comprehension

[i*j for j in range(1, 4)]

For each i, this iterates over j values from 1 to 3 (inclusive), calculating i*j for each j.

The above code produces the multiplication table for numbers 1 through 3.

[[1, 2, 3], # 1*1, 1*2, 1*3
[2, 4, 6],  # 2*1, 2*2, 2*3
[3, 6, 9]]  # 3*1, 3*2, 3*3

Example 2: Flatten a nested list

Convert a 2D list into a 1D list.

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

flattened_list = [num for sublist in nested_list for num in sublist]
print(flattened_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above code example:

(1) Outer list comprehension

[...for sublist in nested_list]

This is the outer list comprehension that iterates through each sublist in nested_list.

sublist will be [1, 2, 3], [4, 5, 6], and finally [7, 8, 9].

(2) Inner list comprehension

num for num in sublist

This is the inner list comprehension that iterates through each num in the current sublist.

It extracts each element from sublist and adds it to the final list flattened_list.

Example 3: With conditional logic

Flatten a 2D list into a 1D list but include only even numbers.

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

flattened_list = [num for sublist in nested_list for num in sublist if num % 2 == 0]
print(flattened_list) # Output: [2, 4, 6, 8]

Nested list comprehensions are concise, but they can become hard to read when overly complex. In such cases, using regular for loop often provides better clarity.