Update appNew update is available. Click here to update.
Last Updated: Oct 16, 2023
Easy

Nested List in Python

Author Ayush Mishra
0 upvote

Introduction

Among all the data structures in Python, a list is used to store a collection of values or items of various types and a sequence of different data types. It is a data type in Python that can hold numerous items of various data types in a single variable.

In this blog, we will discuss the nested list in Python in detail. Let's start going!

nested list python

What is a Nested List in Python? 

Nested list in Python allow a list to contain multiple sublists. Items in each sublist may be of various data types. Comma-separated sublists and items can be combined to create them. The inner lists can again contain other lists thus creating multiple levels of nesting.

The nested lists in Python can be used to create hierarchical data structures, matrices or simply a list of lists. Python has tools for handling nested lists effortlessly and applying standard functions to the nested lists.

How to Create a List in Python

You can create a list using square brackets [] and then add elements inside the brackets, separated by commas. Let's take a look at an example.

  • Python

Python

vegetables = ["carrot", "broccoli", "spinach", "tomato", "cucumber"]
print(vegetables)

 

Output:

output

In this example, we created an array of vegetables and then printed it.

Example of the Nested List in Python:-

The example below creates a nested list ‘mat’ containing two inner lists which represents a 2x3 matrix.

  • Python

Python

mat = [[i for i in range(3)] for j in range(2)]
# Displaying Nested List
print(mat)


Output

Output of Nested Lists

Explanation:

In the above example, we are creating a nested list in Python and showing how nested lists look in Python.

How to Initialize a Nested List in Python

In this part of the nested list in Python, we will see how to access, display, insert, and delete items from the nested list in Python.

Accessing Element of the Nested List

A nested list has multiple indexes that you can use to access specific items. It resembles indexing in a list where the index begins with 0 and ends with list length-1.

An example to access the element of the Nested List in Python is:-

  • Python

Python

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

print(num[2])
# Prints [3, 4, [5, 6]]

print(num[2][2])
# Prints [5, 6]

print(num[2][2][0])
# Prints 5


Output:

Output of accessing element of nested lists

Explanation:

In the above example, we access the element in Python using the element index.

Inserting Element of Nested List

We can use either the append function or the insert function to add items to a nested list. The element or list is appended to the end of the list by the append() function, which accepts it as a parameter. The position at which the item is to be inserted and the element or list to be inserted are the two parameters required by the insert() function.

An example of inserting the element of the Nested List in Python is:-

  • Python

Python

num = [1, 2, [3, 4, [5, 6]], 7, 8]
num.append([8,9,10])
print(num)


Output:

Output of Inserting element of nested lists

Explanation:

In the above example, append() is used to add the elements to the end of the list in Python.

Displaying Element of the Nested List

Let's say we want to show every item in a list. We can use the for or while loop to repeatedly iterate over the elements.

An example of displaying the elements of the Nested List in Python is:-

  • Python

Python

num = [1, 2, [3, 4, [5, 6]], 7, 8]
i=0
for j in num:
   # Printing element key wise
   print(f"{i}: {j}")
   i=i+1


Output:

Output of displaying element of nested lists

Explanation:

In the above example, we are traversing the list using for loop to display each element index-wise in a list.

Must Read Python List Operations

Deleting Element of the Nested List

The Python pop() function or del keyword can remove items or lists from nested lists.

 In Python, the del keyword is used to delete objects, including variables and lists. The pop function removes the final element of a nested list without requiring any parameters.

An example of deleting the element of the Nested List in Python is:-

  • Python

Python

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

# Deleting the third index element
del num[3]
print(num)

# Deleting last element in the list
num.pop()
print(num)


Output:

Output of Deleting element of nested lists

 

You can practice by yourself with the help of online python compiler for better understanding.

Explanation:

In the above example, del is used to delete the third element from the list, and pop() is used to remove the last element from the list.

Flattening Element of the Nested List

It is the method of converting a nested list into a single uniform list. These nested lists are accessed for specific elements by utilizing a filtering condition.

An example of flattening the element of the Nested List in Python is:-

  • Python

Python

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

# Flattening the nested list
f_list = [value for sub in num for value in sub]

print(f_list)


Output:

Output of flattening element of nested lists

Check out Escape Sequence in Python

How to create a nested list from a list in Python?

We can create a nested list from a list in Python using list comprehension. 

Example: Using list comprehension & range() 

  • Python

Python

list1 = [1, 2, 3, 4, 5, 6]
list2 = [[k] for k in list1]
print(list2)

 

Output:

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

 

Explanation

In this example, the original list is [1, 2, 3, 4, 5, 6]. The nested list is created by moving over each element in the original list using list comprehension. Each element k is enclosed in a list [k], thus creating a nested list with each element as a separate sublist.

We can also create nested sublists of a specific size (e.g., creating sublists of size 3 or 2).

Example:

  • Python

Python

list1 = [1, 2, 3, 4, 5, 6]
list2 = [[list1[i], list1[i+1]] for i in range(0, len(list1), 2)]
print(list2)

 

Output:

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

 

Explanation

In the above example, the original list is [1, 2, 3, 4, 5, 6], and we create nested sublists of size 2. The list comprehension moves over the indices of the original list in steps of 2. For each iteration, it extracts three continuous elements from the list1 and creates a sublist with those elements.

Example: Using a for loop 

  • Python

Python

list1 = [10, 20, 30, 40, 50, 60]
list2 = []

for i in range(0, len(list1), 2):
if i + 1 < len(list1):
list2.append([list1[i], list1[i + 1]])

print(list2)

 

Output:

output

 

Explanation:

In the above example, list1 is the original list containing 6 elements and we use the for loop to traverse it two indices at a time and insert sublists of size two into list2. After the loop ends we print the nested list.

Example: Using Numpy 

  • Python

Python

import numpy as np

original_list = [10, 20, 30, 40, 50, 60]
nested_list = np.array(original_list).reshape(-1, 2).tolist()

print(nested_list)

 

Output:

output

 

Explanation:

In the above example, we import the NumPy library and convert the original_list into a NumPy array. Next, we use the reshape() function to reshape the array into a matrix with 2 columns and 3 rows. At last, we convert the resultant NumPy array to a nested list using the .tolist() method.

 

In the next section, we will discuss the advantages and disadvantages of a nested list.

Advantages and Disadvantages of Nested list

The main advantages of using a nested loop in Python are that it is mutable and can be easily replaced or changed with another element while compared to strings and tuples, which are immutable and cannot be changed or replaced. The list can also store data of multiple types.

The disadvantages of the nested list are that they do not support element-wise vector addition and subtraction, and they are slow when compared to the NumPy Array in Python.

Must read: Python Square Root.

Frequently Asked Questions

Q. How do I add an element to a nested list?

To add an element to a nested list in Python, identify the inner list where you want to add the element, then use the append() or extend() method to add element to that inner list.

Q. What is called a nested list?

A nested list in Python allows a list to contain multiple sublists. The inner lists can again contain other lists, creating multiple levels of nesting.

Q. Where is the nested list used?

The nested lists in Python can be used to create hierarchical data structures, matrices, or simply a list of lists. Python provides tools for handling nested lists effortlessly and applying standard functions to nested lists.

Q. How many types of nested lists are there?

The different types of nested lists are, simple nested lists with inner lists at the same nesting level, irregular nested lists (inner lists of different lengths), multi-level nested lists, and mixed data type nested lists.

Conclusion

Congratulations on finishing the blog! We have discussed the nested list in Python. Further, we have discussed working on nested lists in Python with the help of examples.

We hope this blog has helped to enhance your knowledge of the nested list in Python. Do not stop learning! We recommend you read some of our articles related to Python: 

1. Basic of Python

2. Object Oriented Programming in Python

3. Operator  Overloading in Python

4. Fibonacci Series in Python

 

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

We wish you Good Luck! 

Happy Learning!

Previous article
Lists vs Tuples
Next article
Difference Between Lists and Arrays in Python