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 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.
LinkedInRelated Article - Python List
- How to Convert a Dictionary to a List in Python
- How to Remove All the Occurrences of an Element From a List in Python
- How to Remove Duplicates From List in Python
- How to Get the Average of a List in Python
- What Is the Difference Between List Methods Append and Extend
- How to Convert a List to String in Python