×

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

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute 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 Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

How to handle exceptions in python

Prerequisite: Exceptions and errors in Python What are Exceptions? Exceptions are run-time errors that unexpectedly occur and crash a program. When occurred, it alters the flow of the program. These errors are...

9 minutes read.

Python pynmea2

Define Pynmea2 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...

4 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.