×

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of different types and is mutable. A nested list is a list that has another list as a data item in it. These are mostly used to do operations on matrices. A whole other list will occupy a single slot/ index in a list. How amazing is that? This article discusses nested lists and operations on them with examples for a clear view of the concepts.

Syntax

Outer_list = [a, b, c, [nested_list], d, e]

Example program:

list1 = [1, 2, 3, 6]
list2 = [4, 5]
list1. insert (3, list2)
print ("Nested list: ", list1)

Output:

Nested list:  [1, 2, 3, [4, 5], 6]

Understanding:

Using the insert () function, we inserted list2 into list1 at the 3rd index. list2 generally contains 2 elements, but the whole list occupies only the 3rd index in list1.

Accessing the nested list

In the above example, to access the elements of list2, we need to first go to the index of the nested list, then to the index we want inside the nested list:

Syntax:

Outer_list [index of nested list in outer list] [index of element in nested list]

Example:

list1 = [1, 2, 3, [4, 5], 6]
print (list1)
print (list1 [3] [0])
print (list1 [3] [1])

Output:

[1, 2, 3, [4, 5], 6]
4
5

Understanding:

[4, 5] is in the 3rd index of the loop, and we accessed the two elements inside the nested list.

Matrix representation:

Nested List in Python

Lists representation of matrix 3 * 3:

List [0][0]List [0][0]List [0][0]
List [0][0]List [0][0]List [0][0]
List [0][0]List [0][0]List [0][0]

Creating a matrix: (using nested for loop)

list1 = []
for i in range (3):
    list1. append ([])
    for j in range (3):
        list1 [i]. append (j)
for i in list1:
    print (i)

Output:

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

Understanding:

First, we need to create an empty list and append it with nothing till number of rows we need to the matrix. Using another nested for loop, we append the values into the columns of the matrix.

i = 0 -> list1 = [__] -> j = 0 -> list1 = [[0]]

                                      j = 1 -> list1 = [[0, 1]]

                                      j = 2 -> list1 = [[0, 1, 2]]

i = 1 -> list1 = [__, __] -> j = 0 -> list1 = [[0, 1, 2], [0]]

                                            j = 1 -> list1 = [[0, 1, 2], [0, 1]]

                                            j = 2 -> list1 = [[0, 1, 2], [0, 1, 2]]

i = 2 -> list1 = [__, __, __] -> j = 0 -> list1 = [[0, 1, 2], [0, 1, 2], [0]]

                                                   j = 1 -> list1 = [[0, 1, 2], [0, 1, 2], [0, 1]]

                                                   j = 2 -> list1 = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Using list comprehensions, we can achieve the same output but in less number of lines. We can use nested list comprehension to create nested lists.

Using list comprehension:

list1 = [[j for j in range (3)] for i in range (3)]
for i in list1:
    print (i)

Output:

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

Understanding:

We used nested list comprehension to create a nested list. You can observe that we nested a list comprehension inside a list comprehension.

[j for j in range (3)] is nested in [for i in range (3)]

Program to add two matrices

Mat1 = [[11, 12, 13],
        [14, 15, 16],
        [17, 18, 19]]
Mat2 = [[21, 22, 23],
        [24, 25, 26],
        [27, 28, 29]]
sum12 = [[0, 0, 0],
         [0, 0, 0],
         [0, 0, 0]]
for i in range (len (Mat1)):
    for j in range (len (Mat1 [0])):
        sum12 [i][j] = Mat1 [i][j] + Mat2 [i][j]
for i in sum12:
    print (i)

Output:

[32, 34, 36]
[38, 40, 42]
[44, 46, 48]

Understanding:

We kept three lists inside a list representing the three rows, the first element in the three lists representing the first column, etc. We initialized the sum as a zero matrix to update it in the next part of the program. In the outer for loop, i iterates through the length of the matrix-1: 3, which means 0, 1, and 2-represents the rows. In the inner for loop, j iterates through the length of the 0th index of matrix 1-length of the first row-3- represent the number of columns.

  • The outer loop iterates through the rows, and the inner loop iterates through each element in the row.
  • In the above example,

First iteration:

i = 0: j = 0, 1, 2

sum12 [0][0] = Mat1 [0][0] + Mat2 [0][0] -> 11 + 21 = 32

sum12 [0][1] = Mat1 [0][1] + Mat2 [0][1] -> 12 + 22 = 34

sum12 [0][2] = Mat1 [0][2] + Mat2 [0][2] -> 13 + 23 = 36

[11, 12, 13] + [21, 22, 23] = [32, 34, 36]

Second iteration:

i = 1: j = 0, 1, 2

sum12 [1][0] = Mat1 [1][0] + Mat2 [1][0] -> 14 + 24 = 38

sum12 [1][1] = Mat1 [1][1] + Mat2 [1][1] -> 15 + 25 = 40

sum12 [1][2] = Mat1 [1][2] + Mat2 [1][2] -> 16 + 26 = 42

[14, 15, 16] + [24, 25, 26] = [38, 40, 42]

Third iteration:

i = 2: j = 0, 1, 2

sum12 [2][0] = Mat1 [2][0] + Mat2 [2][0] -> 17 + 27 = 44

sum12 [2][1] = Mat1 [2][1] + Mat2 [2][1] -> 18 + 28 = 46

sum12 [2][2] = Mat1 [2][2] + Mat2 [2][2] -> 19 + 29 = 48

[17, 18, 19] + [27, 28, 29] = [44, 46, 48]

Nested lists and nested list comprehension might be confusing in some situations, but it is an important concept and becomes easy once you grasp it.


Related Topics

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Poolmanager in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

CatPlot in Python

Python Seaborn Library Seaborn is a superb Python tool for displaying graphical statistics graphing. Seaborn provides different color schemes and attractive default styles to facilitate the creation of various statistics charts...

8 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

How to Sort a String in Python?

The characters in the string are sorted or put in alphabetical order using the sort string function in Python. Python has built-in techniques for sorting strings available. Since we occasionally...

6 minutes read.