Python - How To Nested List Comprehension in Python

ID : 272

viewed : 89

Tags : PythonPython List

vote vote

100

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.

  • Related HOW TO?