/    /  Nested List comprehensions

## Nested list comprehensions

Nested list comprehensions are the list comprehension inside other list comprehension. The term nested means list containing another list in it. The best example for nested list comprehension is creating a matrix. Let us see an example. Creating a matrix by using list comprehension

Python Code:

``````matrix = []

for i in range(5):

# Append an empty sublist inside the list
matrix.append([])

for j in range(3):
matrix[i].append(j)

print(matrix)
``````

Output:

[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

We can create the same matrix by using nested list comprehension in more simpler way, that is in single line code.

Python Code:

``````matrix = [[j for j in range(3)] for i in range(5)]
print(matrix)
``````

Output:

[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]

In python, by using nested list comprehension we can also flatten already existing list.

Python Code:

``````matrix = [['jan','feb','mar','apr'], ['may','june','july','aug'], ['sep','oct','nov','dec']]

flatten_matrix = []

for sublist in matrix:
for val in sublist:
flatten_matrix.append(val)

print(flatten_matrix)
``````

Output:

[‘jan’, ‘feb’, ‘mar’, ‘apr’, ‘may’, ‘june’, ‘july’, ‘aug’, ‘sep’, ‘oct’, ‘nov’, ‘dec’]

Same as discussed earlier, this flattening of list action can also be done by nested list comprehension in easier way.

Python Code:

``````matrix = [['jan','feb','mar','apr'], ['may','june','july','aug'], ['sep','oct','nov','dec']]

flatten_matrix = [val for sublist in matrix for val in sublist]

print(flatten_matrix)
``````

Output:

[‘jan’, ‘feb’, ‘mar’, ‘apr’, ‘may’, ‘june’, ‘july’, ‘aug’, ‘sep’, ‘oct’, ‘nov’, ‘dec’]