Nested Lists in Python | Detailed Guide

The data structure named list is utilized to store or keep the collection of data with different data types, unlike an array in Python. The list contains various elements separated by a comma and placed inside the square bracket. In Python, a list containing single or multiple lists as its elements is referred to as a nested list.

In this Python post, we will illustrate an in-depth guide on nested lists using various examples. The below contents will be explained in this post:

Create Nested Lists in Python

The following code shows how to create a nested list in Python:

Code:

nested_lists = [[55,45], [43, 44]]
print(nested_lists)

A nested list is created by enclosing the lists inside the square brackets.

Output:

The nested list has been created successfully.

Access Nested Lists in Python

To access the nested lists in Python, you can utilize the following code:

Code:

nested_lists = [[55,45,[455, 555]], [43, 44]]
print(nested_lists)
print(nested_lists[0])
print(nested_lists[0][2])
print(nested_lists[0][2][1])
  • The “nested_lists” containing multiple lists are created in the program.
  • The lists inside the nested list can be accessed using the square bracket notation such as “nested_lists[0]” is used to access the nested list placed at index 0.

Output:

The nested lists have been accessed using the index value.

Add Elements Value to a Nested List

To add an element value to the nested list the “append()” function is used in Python. Here is an example:

Code:

nested_lists = [[55,45,[455, 555]], [43, 44]]
print(nested_lists)
nested_lists.append('45')
nested_lists[0].append('20')
print(nested_lists)
  • The nested lists are initialized in the program.
  • The “list.append()” function is used to add/insert an element at the end of the nested list.
  • To add the element to a particular inner list of a nested list the index position of that list should be passed inside the square bracket.

Output:

The above snippet shows that the elements have been added to nested lists.

Convert Nested Lists Into One List

The list comprehension method is used in the below code to convert the nested list into one list:

Code:

nested_lists = [[45, 25, 30], [13, 15, 21]]
output = [z for l in nested_lists for z in l]
print(output)

The for loop is used inside the list comprehension to iterate over the list and return one single list.

Output:

The nested list has been converted into one list.

Remove Elements From a Nested List

The following code uses the “pop()” function to remove elements from the nested lists:

Code:

nested_lists = [[45, 25, 30], [13, 15, 21]]
nested_lists[1].pop(1)
print(nested_lists)
nested_lists.pop(0)
print(nested_lists)
  • The “pop()” function is used to remove the element from the nested list using a specific index position.
  • The expression “nested_lists[1].pop(1)” is used to remove the first element of the nested list.

Output:

The above output verified that the list element has been removed.

Find Nested List Length Using len() Function

The below code is used to find the length of the nested list using the “len()” function:

Code:

nested_lists = [[45, 25, 30], [13, 15, 21]]
print(len(nested_lists))
print(len(nested_lists[0]))

The “len()” function takes the nested list variable and returns the length of the nested list.

Output:

The length of the nested list has been shown in the above snippet.

Convert Nested Lists to Dictionary

To convert nested lists to the dictionary the following code is used in Python:

Code:

nested_lists = [['Joseph', 'Henry', 'Anna'],[25, 33, 10],
                ['White', 'Black', 'Blue']]
output = {x[0]: x[1:] for x in nested_lists}
print(output)
print(type(output))
  • The dictionary list comprehension method is used to create the key-value pair of the given nested list.
  • The “x[0]” returns the first element of all nested lists as a key of the dictionary and “x[1:]” returns the element other than the first element as a value of the dictionary key.

Output:

The given nested lists have been converted into a dictionary.

Convert Nested Lists to Numpy Array

The “np.array()” function is used to convert the nested lists to a numpy array. Here is an example code:

Code:

import numpy
nested_lists = [[55, 45, 65], [5, 45, 54], [49, 85, 95]]
output = numpy.array(nested_lists)
print(output)

The “np.array()” function accepts the nested lists and converts them into a numpy array.

Note: The lists initialized in the nested lists must be of the same length.

Output:

The given nested list has been created into the numpy array.

Convert Nested Lists to Dataframe

The nested list can be converted into DataFrame using the “pd.DataFrame()” function. The below code is used to convert nested lists to DataFrame:

Code:

import pandas as pd
nested_lists = [['Joseph', 'Henry', 'Anna'],[25, 33, 10],
                ['White', 'Black', 'Blue']]
print(pd.DataFrame(nested_lists))

The “pd.DataFrame()” function takes the nested lists as an argument and returns the DataFrame of the given lists.

Output:

The nested lists have been converted into a DataFrame.

Convert Nested Lists to Lists of Tuples

The “tuple()” function is used with for loop to convert the nested lists to list of tuples in Python:

Code:

nested_lists = [[55, 45, 65], [5, 45, 54], [49, 85, 95]]
output = [tuple(x) for x in nested_lists]
print(output)

The for loop iterates over the nested lists and the “tuple()” function is used to convert each list into a tuple.

Output:

The above output shows that the nested value has been converted into a list of tuples.

Convert Nested Lists to CSV File

The below code uses the “csv” module to convert the nested lists to a CSV file:

Code:

import csv
nested_lists = [['Joseph', 25, 'White'],['Henry', 33, 'Black'],
                ['Anna', 10, 'Blue']]
with open('ILF.csv', 'w', newline='') as file:
    data = csv.writer(file)
    data.writerows(nested_lists)
  • The “csv” module is imported into the program.
  • The nested lists containing multiple lists are initialized in the program.
  • The “open()” function is used to create the “CSV” file and set the file in “w” or writing mode.
  • The “csv.writerows()” function is used to write the nested list into a CSV file.

Output:

The above output shows that the given nested list has been converted into a CSV file.

Sort Nested Lists by Key

To sort nested lists the “sort()” function is used in Python, as shown in the following code:

Code:

nested_lists = [[55, 15], [10, 20, 30], [50], [1, 0], [0, 0], [24, 2]]
nested_lists.sort()
print(nested_lists)

The “sort()” function is used without any parameter value to sort the list in ascending order (according to the first element of the list).

Output:

The nested list has been sorted.

We can also use the “key” parameter of the “sort()” function to sort the list according to the key value. Here is an example:

Code:

nested_lists = [[55, 15], [10, 20, 30, 43], [50],
                [11, 10, 0], [0, 0], [24, 2]]
nested_lists.sort(key=len)
print(nested_lists)

The “sort()” function takes the “key=len” parameter and returns the nested list according to the length of the list.

Output:

The nested list has been sorted according to the length of the list.

Reverse Nested Lists in Python

To reverse the nested lists the “reverse()” function is used in Python. Here is an example:

Code:

nested_lists = [[45, 55, 65, 25], [54, 32, 65, 75], [45, 65], [55]]
nested_lists.reverse()
print(nested_lists)

The nested list is reversed using the “reverse()” function.

Output:

The above output shows that the nested list has been successfully reversed.

Conclusion

The Python nested lists or list of lists is created using the square bracket notation. The nested lists can be accessed using the index position. We can perform multiple operations on nested lists such as adding elements to a list, removing elements from the list, reversing nested lists, etc. The nested list can also be converted into CSV and DataFrame using CSV and Pandas Module. This Python post delivered an in-depth overview of nested lists or lists of lists using multiple examples.