How do you make a nested list dynamically in python?

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]

How do you make a nested list dynamically in python?




Article Tags :

Python

Technical Scripter

python-list

Technical Scripter 2018

Practice Tags :

python-list

How do I create a dynamic nested list in python?

You can get python to generate separate-but-identical lists for each row by using a list comprehension. When you use [rowexpr for i in xrange(height)] then rowexpr will be evaluated once per row. The trick then is to use an expression that will result in a unique list each time it is evaluated.

How to get dynamic keys from JSON data?

0. Add a comment. |. 2. Here is a simple example to get dynamic keys from json response – Get dynamic keys from JSON Data. public void getData (String data) { // Load json data and display JSONObject jsonData = new JSONObject (data); // Use loop to get keys from your response Iterator itr = jsonData.keys (); while (itr.hasNext ()) …

Wrong way to create & initialize a list of lists in python

Let’s start from basic, quickest way to create and initialize a normal list with same values in python is,

# Creating a list with same values list_of_num = [5]* 10 print(list_of_num)
Output:
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
It created a list of size 10 with the same element i.e. 5. Basically it copied the object inside [], 10 times. Let’s use same logic to create and initialize a list of lists,
# Create a list with 4 references of same sub list list_of_num = [[]] * 4 print('List of lists:') print(list_of_num)
Output:
[[], [], [], []]
Here we provided an empty list [] inside the [] and multiplied it by 4. It created 4 different references of [] and inserted them into a new list. Yes, these are not 4 empty lists inside the main list, but these are not different list objects instead these are mere references of first list. Let’s confirm this by iterating over the list and printing id of each sub list object,
for elem in list_of_num: print(id(elem))
Output:
200792200 200792200 200792200 200792200
All entries in the list have the same ID i.e. they point to the same list object.

Why does it matter ?

Let’s inserting an element in the 3rd sub list of main list i.e.

# Insert 11 into the 3rd sub list list_of_num[2].append(11)
Now check the contents of the main list,
print('Modified list of lists:') print(list_of_num)
Output:
Modified list of lists: [[11], [11], [11], [11]]
Element was inserted in all the sub lists, because these are not different lists. We didn’t expect this at first place, we just wanted to insert the element in the 3rd sub-list. So, it proves that this is a wrong way to create and initialize a list of list. Let’s look at the correct way,

Advertisements

How do I merge nested lists in python?

First, flatten the nested lists. Take Intersection using filter() and save it to ‘lst3’. Now find elements either not in lst1 or in lst2, and save them to ‘temp’. Finally, append ‘temp’ to ‘lst3’.

How do I join a nested list?

Straightforward way is to run two nested loops – outer loop gives one sublist of lists, and inner loop gives one element of sublist at a time. Each element is appended to flat list object.

How do I make a nested list one list in Python?

The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in python list, all the nested has to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside.

List in Python

Learn about List in Python

Z

Zeeshan Abbasi

27 Aug 2021-13 mins read

Lists and Tuples in Python

by John Sturtz basics python

Mark as Completed

Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Lists and Tuples in Python

Lists and tuples are arguably Python’s most versatile, useful data types. You will find them in virtually every nontrivial Python program.

Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples. You’ll learn how to define them and how to manipulate them. When you’re finished, you should have a good feel for when and how to use these object types in a Python program.

Take the Quiz: Test your knowledge with our interactive “Python Lists and Tuples” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »