Table of contents
1.
Introduction
2.
What is a Nested List in Python? 
3.
How to Create a List in Python
3.1.
Python
4.
Example of the Nested List in Python:-
4.1.
Python
5.
How to Initialize a Nested List in Python
5.1.
Accessing Element of the Nested List
5.2.
Python
5.3.
Inserting Element of Nested List
5.4.
Python
5.5.
Displaying Element of the Nested List
5.6.
Python
5.7.
Deleting Element of the Nested List
5.8.
Python
5.9.
Flattening Element of the Nested List
5.10.
Python
6.
How to create a nested list from a list in Python?
6.1.
Example: Using list comprehension & range() 
6.2.
Python
6.3.
Python
6.4.
Example: Using a for loop 
6.5.
Python
6.6.
Example: Using Numpy 
6.7.
Python
7.
Advantages of Nested list
8.
Disadvantages of Nested Lists
9.
Frequently Asked Questions
9.1.
Q. How do I add an element to a nested list?
9.2.
Q. What is called a nested list?
9.3.
Q. Where is the nested list used?
9.4.
Q. How many types of nested lists are there?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Nested List in Python

Author Ayush Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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)
You can also try this code with Online Python Compiler
Run Code

 

Output:

output

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

Also see, Python Filter Function

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)
You can also try this code with Online Python Compiler
Run Code


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
You can also try this code with Online Python Compiler
Run Code


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)
You can also try this code with Online Python Compiler
Run Code


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
You can also try this code with Online Python Compiler
Run Code


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)
You can also try this code with Online Python Compiler
Run Code


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)
You can also try this code with Online Python Compiler
Run Code


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)
You can also try this code with Online Python Compiler
Run Code

 

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)
You can also try this code with Online Python Compiler
Run Code

 

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)
You can also try this code with Online Python Compiler
Run Code

 

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)
You can also try this code with Online Python Compiler
Run Code

 

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 of Nested list

Nested lists offer several advantages for data organization and manipulation:

  • Hierarchical Data Representation: They excel at representing data with inherent hierarchies. Imagine an organizational chart, family tree, or bill of materials. Each level of the hierarchy can be a sublist within the main list.
  • Complex Data Structures: Nested lists can create intricate data structures that go beyond simple flat lists. For example, a list of students can have sublists containing their names, grades, and course information.
  • Flexible Data Storage: Each element in the outer list can hold various data types, including other lists. This versatility allows you to store diverse datasets within a single nested list structure.
  • Multi-dimensional Arrays: Nested lists can effectively represent multi-dimensional arrays, like matrices or grids. The outer list represents rows, and inner lists represent columns.

Disadvantages of Nested Lists

While powerful, nested lists also have some drawbacks:

  • Increased Complexity: Deeply nested lists can become complex and challenging to navigate and understand, especially for larger datasets.
  • Potential for Errors: Accessing and manipulating elements within nested structures can be error-prone, requiring careful indexing to avoid mistakes.
  • Performance Overhead: Nested lists might have slower performance compared to specialized data structures like NumPy arrays for numerical computations due to memory management.
  • Readability: Very nested lists can become difficult to read and maintain, especially for someone unfamiliar with the data structure.

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!

Live masterclass