Do you think IIT Guwahati certified course can help you in your career?
No
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!
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.
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
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:-
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
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
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
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
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.
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.
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: