Nested Lists in Python

Nested Lists in Python

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
a=[3,5,8,4,15,34,[5,8,[-4,-8],9,3], 8,9,[6,9],12,7].
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[0], and if you check its type it will be int.
Element 5 can be accessed using the index a[1], and if you check its type it will be int.
It will be continued till 34 which can be accessed using index a[5] 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[6] and if you check the type of
a[6] it will be a list.
And a[6] contains its own elements 5,8,[-4,-8],9,3 which will be index as a[6][0], a[6][1], a[6][2], a[6][3], a[6][4]. In which you can observe that a[6][2] is also a list object and its elements will be accessed as a[6][2][0] and a[6][2][1].

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.

Nested Lists in Python

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)):
if type(a[i])==list:
for j in range(len(a[i])):
if type(a[i][j])==list:
for k in range(len(a[i][j])):
print(‘Elements of List[List[List]]’,a[i][j][k])
else:
print(‘Elements of List[List’,a[i][j])
else:
print(a[i])


 

Share to Your Friend
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Comment