Nested Lists in Python
List in Python is a powerful data structure and it allows arbitrary numbers of nested lists in Python. However, problems you will face to access them using loops. In this post, I have explained how to access nested list of elements.
Suppose you have a nested list
To understand how to access elements of nested list, you have to understand indexing of objects of a list.
Element 3 can be accessed using the index a, and if you check its type it will be int.
Element 5 can be accessed using the index a, and if you check its type it will be int.
It will be continued till 34 which can be accessed using index a if you check its type it will be int.
What happens when a list comes as an object of a list Python also indexes this list [5,8,[-4,-8],9,3] as a and if you check the type of
a it will be a list.
And a contains its own elements 5,8,[-4,-8],9,3 which will be index as a, a, a, a, a. In which you can observe that a is also a list object and its elements will be accessed as a and a.
So, you have understood that how indexing works in nested lists.
There three level of nesting in list a so your program will require three for loops. And below for loop type of objects will be checked if it is
also a list then it will require another for loop to access elements of nested list.
You can see program and its output in Jupyter notebook.
Python Program to Access Two Level of Nested List
If you want to run it yourself the Python’s code is given below.
a=[3, 5, 8, 4, 15, 34, [5,8, [-4, -8], 9, 3], 8, 9, [6,9], 12, 7]
for i in range(len(a)):
for j in range(len(a[i])):
for k in range(len(a[i][j])):
print(‘Elements of List[List[List]]’,a[i][j][k])
print(‘Elements of List[List’,a[i][j])