 # Python – Nested List Comprehensions

## Nested List Comprehensions in Python

List Comprehensions 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.

Let’s take a look at some examples to understand what nested list comprehensions can do:

Example 1:

```I want to create a matrix which looks like below:

matrix = [[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]]
```

The below code uses nested for loops for the given task:

 `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]]
```

The same output can be achieved using nested list comprehension in just one line:

 `# 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]]
```

Explanation:

The syntax of the above program is shown below:

[expression for i in range(5)] –> which means that execute this expression and append its output to the list until variable i iterates from 0 to 4.

For example:- [i for i in range(5)] –> In this case, the output of the expression
is simply the variable i itself and hence we append its output to the list while i
iterates from 0 to 4.

Thus the output would be –> [0, 1, 2, 3, 4]

But in our case, the expression itself is a list comprehension. Hence we need to first
solve the expression and then append its output to the list.

expression = [j for j in range(5)] –> The output of this expression is same as the
example discussed above.

Hence expression = [0, 1, 2, 3, 4].

Now we just simply append this output until variable i iterates from 0 to 4 which would
be total 5 iterations. Hence the final output would just be a list of the output of the
above expression repeated 5 times.

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:

```Suppose I want to flatten a given 2-D list:

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

Expected Output: flatten_matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9]
```

This can be done using nested for loops as follows:

 `# 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]
```

Again this can be done using nested list comprehension which has been shown below:

 `# 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]
```

Explanation:

In this case, we need to loop over each element in the given 2-D list and append it
to another list. For better understanding, we can divide the list comprehension into
three parts:

```flatten_matrix = [val
for sublist in matrix
for val in sublist]```

The first line suggests what we want to append to the list. The second line is the
outer loop and the third line is the inner loop.

‘for sublist in matrix’ returns the sublists inside the matrix one by one which would be:

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

‘for val in sublist’ returns all the values inside the sublist.

Hence if sublist = [1, 2, 3], ‘for val in sublist’ –> gives 1, 2, 3 as output one by one.

For every such val, we get the output as val and we append it to the list.

Example 3:

Suppose I want to flatten a given 2-D list and only include those strings whose lengths are less than 6:

planets = [[‘Mercury’, ‘Venus’, ‘Earth’], [‘Mars’, ‘Jupiter’, ‘Saturn’], [‘Uranus’, ‘Neptune’, ‘Pluto’]]

Expected Output: flatten_planets = [‘Venus’, ‘Earth’, ‘Mars’, ‘Pluto’]

This can be done using an if condition inside a nested for loop which is shown below:

 `# 2-D List of planets` `planets ``=` `[[``'Mercury'``, ``'Venus'``, ``'Earth'``], [``'Mars'``, ``'Jupiter'``, ``'Saturn'``], [``'Uranus'``, ``'Neptune'``, ``'Pluto'``]]` ` ` `flatten_planets ``=` `[]` ` ` `for` `sublist ``in` `planets:` `    ``for` `planet ``in` `sublist:` `         ` `        ``if` `len``(planet) < ``6``:` `            ``flatten_planets.append(planet)` `         ` `print``(flatten_planets)`

Output:

```['Venus', 'Earth', 'Mars', 'Pluto']
```

This can also be done using nested list comprehensions which has been shown below:

 `# 2-D List of planets` `planets ``=` `[[``'Mercury'``, ``'Venus'``, ``'Earth'``], [``'Mars'``, ``'Jupiter'``, ``'Saturn'``], [``'Uranus'``, ``'Neptune'``, ``'Pluto'``]]` ` ` `# Nested List comprehension with an if condition` `flatten_planets ``=` `[planet ``for` `sublist ``in` `planets ``for` `planet ``in` `sublist ``if` `len``(planet) < ``6``]` `         ` `print``(flatten_planets)`

Output:

```['Venus', 'Earth', 'Mars', 'Pluto']
```

Explanation:

This example is quite similar to the previous example but in this example, we just
need an extra if condition to check if the length of a particular planet is less than
6 or not.

This can be divided into 4 parts as follows:

```flatten_planets = [planet
for sublist in planets
for planet in sublist
if len(planet) < 6]
```

Last Updated on October 25, 2021 by admin

## Best Python libraries for Machine LearningBest Python libraries for Machine Learning

Best Python libraries for Machine Learning Machine Learning, as the name suggests, is the science of programming a computer by which they are able to learn from different kinds of data. A more general definition given by Arthur Samuel is

## Python append() functionPython append() function

Python append() function Append function Adds its argument as a single element to the end of a list. The length of the list increases by one. syntax: # Adds an object (a number, a string or a # another list)

## Python String ConcatenationPython String Concatenation

Python String Concatenation In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets [] can be used to access

## Python – os.path.dirname() methodPython – os.path.dirname() method

Python | os.path.dirname() method OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python

## How to combine two dataframe in Python – Pandas?How to combine two dataframe in Python – Pandas?

How to combine two dataframe in Python – Pandas? In many real-life situations, the data that we want to use comes in multiple files. We often have a need to combine these files into a single DataFrame to analyze the

## When to use yield instead of return in Python?When to use yield instead of return in Python?

When to use yield instead of return in Python? The yield statement suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the

## dir() function in Pythondir() function in Python

dir() function in Python dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any object (say functions , modules, strings, lists, dictionaries etc.) Syntax : dir({object}) Parameters :   object [optional] : Takes

## Python – Output FormattingPython – Output Formatting

Python – Output Formatting There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Sometimes user