Nested List Comprehension in Python

Nested List Comprehension in Python

Lakshay Kapoor Aug-10, 2021 Jun-17, 2021 Python Python List
  1. List Comprehension in Python
  2. 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.

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • What Is the Difference Between List Methods Append and Extend
  • Convert a List to String in Python