Open In App

Nested List Comprehensions in Python

Last Updated : 13 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

List Comprehension are one of the most amazing features of Python. It is a smart and concise way of creating lists by iterating over an iterable object. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops.

Nested List Comprehension in Python Syntax

Below is the syntax of nested list comprehension:

Syntax: new_list = [[expression for item in list] for item in list]

Parameters:

  • Expression: Expression that is used to modify each item in the statement
  • Item: The element in the iterable
  • List: An iterable object

Python Nested List Comprehensions Examples

Below are some examples of nested list comprehension:

Example 1: Creating a Matrix

In this example, we will compare how we can create a matrix when we are creating it with

Without List Comprehension

In this example, a 5×5 matrix is created using a nested loop structure. An outer loop iterates five times, appending empty sublists to the matrix, while an inner loop populates each sublist with values ranging from 0 to 4, resulting in a matrix with consecutive integer values.

Python3




matrix = []
for i in range(5):
    # Append an empty sublist inside the list
    matrix.append([])
    for j in range(5):
        matrix[i].append(j)
print(matrix)


Output

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

Using List Comprehension

The same output can be achieved using nested list comprehension in just one line. In this example, a 5×5 matrix is generated using a nested list comprehension. The outer comprehension iterates five times, representing the rows, while the inner comprehension populates each row with values ranging from 0 to 4, resulting in a matrix with consecutive integer values.

Python3




# Nested list comprehension
matrix = [[j for j in range(5)] for i in range(5)]
 
print(matrix)


Output

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

Example 2: Filtering a Nested List Using List Comprehension

Here, we will see how we can filter a list with and without using list comprehension.

Without Using List Comprehension

In this example, a nested loop traverses a 2D matrix, extracting odd numbers from Python list within list and appending them to the list odd_numbers. The resulting list contains all odd elements from the matrix.

Python3




matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
odd_numbers = []
for row in matrix:
    for element in row:
        if element % 2 != 0:
            odd_numbers.append(element)
 
print(odd_numbers)


Output

[1, 3, 5, 7, 9]

Using List Comprehension

In this example, a list comprehension is used to succinctly generate the list odd_numbers by iterating through the elements of a 2D matrix. Only odd elements are included in the resulting list, providing a concise and readable alternative to the equivalent nested loop structure.

Python3




matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
odd_numbers = [
    element for row in matrix for element in row if element % 2 != 0]
 
print(odd_numbers)


Output

[1, 3, 5, 7, 9]

Example 3: Flattening Nested Sub-Lists

Without List Comprehension

In this example, a 2D list named matrix with varying sublist lengths is flattened using nested loops. The elements from each sublist are sequentially appended to the list flatten_matrix, resulting in a flattened representation of the original matrix.

Python3




# 2-D List
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
 
flatten_matrix = []
 
for sublist in matrix:
    for val in sublist:
        flatten_matrix.append(val)
 
print(flatten_matrix)


Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

With List Comprehension

Again this can be done using nested list comprehension which has been shown below. In this example, a 2D list named matrix with varying sublist lengths is flattened using nested list comprehension. The expression [val for sublist in matrix for val in sublist] succinctly generates a flattened list by sequentially including each element from the sublists.

Python3




# 2-D List
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
 
# Nested List Comprehension to flatten a given 2-D matrix
flatten_matrix = [val for sublist in matrix for val in sublist]
 
print(flatten_matrix)


Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 4: Manipulate String Using List Comprehension

Without List Comprehension

In this example, a 2D list named matrix containing strings is modified using nested loops. The inner loop capitalizes the first letter of each fruit, and the outer loop constructs a new 2D list, modified_matrix, with the capitalized fruits, resulting in a matrix of strings with initial capital letters.

Python3




matrix = [["apple", "banana", "cherry"],
          ["date", "fig", "grape"],
          ["kiwi", "lemon", "mango"]]
 
modified_matrix = []
for row in matrix:
    modified_row = []
    for fruit in row:
        modified_row.append(fruit.capitalize())
    modified_matrix.append(modified_row)
 
print(modified_matrix)


Output

[['Apple', 'Banana', 'Cherry'], ['Date', 'Fig', 'Grape'], ['Kiwi', 'Lemon', 'Mango']]

With List Comprehension

In this example, a 2D list named matrix containing strings is transformed using nested list comprehension. The expression [[fruit.capitalize() for fruit in row] for row in matrix] efficiently generates a modified matrix where the first letter of each fruit is capitalized, resulting in a new matrix of strings with initial capital letters.

Python3




matrix = [["apple", "banana", "cherry"],
          ["date", "fig", "grape"],
          ["kiwi", "lemon", "mango"]]
 
modified_matrix = [[fruit.capitalize() for fruit in row] for row in matrix]
 
print(modified_matrix)


Output

[['Apple', 'Banana', 'Cherry'], ['Date', 'Fig', 'Grape'], ['Kiwi', 'Lemon', 'Mango']]


Previous Article
Next Article

Similar Reads

Python List Comprehensions vs Generator Expressions
What is List Comprehension? It is an elegant way of defining and creating a list. List Comprehension allows us to create a list using for loop with lesser code. What normally takes 3-4 lines of code, can be compressed into just a single line. Example: # initializing the list list = [] for i in range(11): if i % 2 == 0: list.append(i) # print elemen
3 min read
Reducing Execution time in Python using List Comprehensions
Prerequisites: Comprehensions in Python Most of the competitive programmers who code in Python often face difficulty in executing the programs within the given time limit. List Comprehensions help us in reducing the execution time of a program where you are required to create a list based on any mathematical expression. We will consider an example
2 min read
4 Tips To Master Python List Comprehensions
Python's list comprehensions offer a concise and powerful way to create lists. They allow you to express complex operations in a single line of code, making your code more readable and efficient. In this article, we will explore four tips to master Python list comprehensions with five commonly used examples. 4 Tips To Master Python List Comprehensi
4 min read
Comprehensions in Python
Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, sets, dictionaries, etc.) using previously defined sequences. Python supports the following 4 types of comprehension: List ComprehensionsDictionary ComprehensionsSet ComprehensionsGenerator ComprehensionsList ComprehensionsList Comprehensions
6 min read
Scala For Comprehensions
Comprehensions have the structure for (enumerators) yield e, wherever enumerators refers to a semicolon-separated list of enumerators. Enumerator is either a generator that introduces new variables, or it's a filter. A comprehension evaluates the body e for every binding generated by the enumerators and returns a sequence of those values. These def
3 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Pair and combine nested list to tuple list
Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the solution of this problem. Method #1 : Using zip()
10 min read
Python | Find maximum length sub-list in a nested list
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length). Examples: Input : [['A'], ['A', 'B'], ['A', 'B', 'C']] Output : (['A', 'B', 'C'], 3) Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]] Output : ([1, 2, 3, 9, 4], 5) Let's discuss different approaches to solve this prob
3 min read
Python | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() The combination of above functional
7 min read
Python - Convert List to custom overlapping nested list
Given a list, the task is to write a Python program to convert it into a custom overlapping nested list based on element size and overlap step. Examples: Input: test_list = [3, 5, 6, 7, 3, 9, 1, 10], step, size = 2, 4Output: [[3, 5, 6, 7], [6, 7, 3, 9], [3, 9, 1, 10], [1, 10]]Explanation: Rows sliced for size 4, and overcoming started after 2 eleme
3 min read
Practice Tags :