Nested list comprehension in python

PythonServer Side ProgrammingProgramming

A nested list is a list within a list. Python provides features to handle nested list gracefully and apply common functions to manipulate the nested lists. In this article we will see how to use list comprehension to create and use nested lists in python.

Creating a Matrix

Creating a matrix involves creating series of rows and columns. We can use for loop for creating the matrix rows and columns by putting one python list with for loop inside another python list with for loop.

Example

 Live Demo

matrix = [[m for m in range(4)] for n in range(3)]
print(matrix)

Running the above code gives us the following result:

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

Filtering from Nested List

We can use the list comprehension with filtering feature by using the for loop within the sub-lists. Below we have a 2 dimensional list with one layer of sub-list inside a bigger list. We access selective elements from each of these nested lists. By using a filter condition.

Example

 Live Demo

years = [['January', 'February', 'March'], ['April', 'May', 'June'], ['July', 'August', 'September'],['October','November','December']]
# Nested List comprehension with an if condition
years = [years for sublist in years for years in sublist if len(years) <= 5]
print(years)

Running the above code gives us the following result:

['March', 'April', 'May', 'June', 'July']

Flattening nested Sub-Lists

We can also take a nested list and flatten it by creating a single list without having any sub-list inside it.

Example

 Live Demo

nested_list = [[1] ,[17, 19], [21,23,25], [32,35,37,39]]
# Nested List Comprehension to flatten a given 2-D matrix
flattened_list = [value for sublist in nested_list for value in sublist]
print(flattened_list)

Running the above code gives us the following result:

[1, 17, 19, 21, 23, 25, 32, 35, 37, 39]
raja
Published on 30-Dec-2019 10:32:32
Advertisements