Nested List Comprehension in Python

Lakshay Kapoor Oct 10, 2023
  1. List Comprehension in Python
  2. Nested List Comprehension in Python
Nested List Comprehension in Python

This article talks about the significance of the nested list comprehension in Java. We’ve also included example programs to show you how you can use this function in a process.

List Comprehension in Python

In Python, the list comprehension is one of the easiest methods for creating new lists by using the elements present in an already-made list. For example, one can create a list containing cars from a list containing all kinds of automobiles.

Nested List Comprehension in Python

The nested list comprehension is just like the nested for loops. The nested list comprehension is a list comprehension inside another list comprehension.

Example:

array = [[2, 4, 6], [8, 10, 12], [14, 16, 18, 20]]
print([b for a in array for b in a])

Output:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

In the program above, a single list has been created using a two-dimensional array containing three lists. Therefore, a new list is created using already existing lists.

Here is another example of nested list comprehension.

array = [[a for a in range(4)] for b in range(6)]
print(array)

Output:

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

Here, a two-dimensional array is created using the range() function. The range() command is used to return a sequence that starts with 0 by default; it also keeps on increasing by 1 by default. The number placed as the function’s argument is the endpoint of the sequence of numbers; the sequence of numbers stops before the mentioned number.

Here, the first list comprehension is the number of elements present in each list in the two-dimensional array. The list comprehension outside the first list comprehension is the number of lists present in the two-dimensional array.

Lakshay Kapoor avatar Lakshay Kapoor avatar

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.

LinkedIn

Related Article - Python List