Nested List in Python

In this tutorial, we will understand how to implement a nested List in Python. Before that let us understand list in Python. List in Python is a data type that can store multiple items of different data types into a single variable.

One of the significant advantages of using lists over any other data type like tuples or string is that list is mutable. Therefore, an item inside the list can be easily changed or replaced with any other element. Following is an example of a simple list in python that stores a list of products displayed by any e-commerce website.

print(f"Displaying products offered by our website: {products}")
print(f"Acessing 2nd product of list: {products[1]}")
Displaying products offered by our website: ['books', 'toys', 'kitchenware']
Acessing 2nd product of list: toys

Sometimes, it becomes necessary to add more sublists within the same list with each list storing items of different data types. In our example, suppose we want to store products along with the number of units for each type of product. Also for each item such as books, we want to further associate categories for that product. In this scenario using normal lists would not be a valid option and hence we move to nested lists.

Nested Lists in Python

A nested list in python allows a list to contain multiple sublists within itself. Each sublist can have items of different data types. It can be created by placing comma-separated sublists and items together. Following is an example of a nested list in python satisfying the above-mentioned criteria.

print(f"Displaying products offered by our website: {products}")
Displaying products offered by our website: [['books', ['comedy', 'horror'], 'toys', 'kitchenware'], [200, 100, 350]]

Accessing elements of nested List

Suppose we want to access the comedy category from the category sublist of the e-commerce list. It is similar to indexing in the list where the index starts with 0 and ends with length of list-1. The following diagram explains the entire structure of indexing in our example of an e-commerce list.

The following code explains how to access the horror category from the category sublist. Here we are accessing the first list. Within the first list, we want the second item which is again a sublist. Within that sublist, we want the second item.

print(f"Displaying second book category: {book_category}")
Displaying second book category: horror

Displaying items of the nested List

Suppose we want to display all the items from the category sublist of the e-commerce list. To iterate over the elements we can make use of the for or while loop.

for category in ecommerce[0][1]:
    print(f"Category  {index}: {category}")
Category  0: comedy
Category  1: horror

Inserting an item into a nested list

In order to add items to a nested list, we can make use of either the append function or insert function. The append() function takes the element or list as a parameter and appends it to the end of the list. The insert() function takes two parameters- the position at which the item is to be inserted and the element or list to be inserted. The following code explains the insertion of elements to a list using the append and the insert function.

# Using insert to add one more product

#Using append to add discount offered on each type of product
[['books', ['comedy', 'horror'], 'toys', 'clothes', 'kitchenware'], [200, 100, 350]]
[['books', ['comedy', 'horror'], 'toys', 'clothes', 'kitchenware'], [200, 100, 350], ['20%', '10%', '50%', '5%']]‚Äč

In the above code, we used the insert function to add one more type of product named ‘clothes’ at the 3rd index of the e-commerce[0] list. Here e-commerce[0] will give the list at index position zero of the e-commerce list.

Deleting items from a nested list

To delete items or lists from a nested list in python we can make use of the pop() function or del keyword. The del keyword is used to delete objects in python which can range anything from variables or lists. The pop function takes no parameters and simply deletes the last element of the nested list. In the below-mentioned code, we have used the del keyword the delete 3rd item from the first sublist of the e-commerce list. Similarly, we made use of the pop function to delete the discount sub-list.

# Using del to delete one product
del ecommerce[0][3]

#Using pop to delete discount offered on each type of product
[['books', ['comedy', 'horror'], 'toys', 'kitchenware'], [200, 100, 350]]
[['books', ['comedy', 'horror'], 'toys', 'kitchenware']]

Flatten nested List in Python

Flattening a nested list is converting it to a single uniform list. Various methods can be employed to flatten a nested list in python. In the below-mentioned code, I have made use of the list comprehension strategy to flatten the nested list. The for loop shall over each item of each sublist and return the item as the output in a single list.

result=[item for list1 in ecommerce for item in list1]
['books', 'toys', 'clothes', 'kitchenware', 200, 100, 350]

This is the end of the tutorial on how to implement a nested list in Python. You can read further on the nested dictionary in Python using the following link: Nested Dictionary in Python

Leave a Reply

Your email address will not be published. Required fields are marked *