How to iterate through a nested List in Python?
Last Updated :
08 Dec, 2020
In this article, we are going to see how to iterate through a nested List. A list can be used to store multiple Data types such as Integers, Strings, Objects, and also another List within itself. This sub-list which is within the list is what is commonly known as the Nested List.
Iterating through a Nested List
Lets us see how a typical nested list looks like :
There are multiple ways to iterate through a Nested List:
Method 1: Use of the index to iterate through the list
Use of Positive Index:
Python3
list = [ 10 , 20 , 30 , 40 , [ 80 , 60 , 70 ]]
print ( list [ 4 ])
print ( list [ 4 ][ 0 ])
print ( list [ 4 ][ 1 ])
print ( list [ 4 ][ 2 ])
|
Output:
[80, 60, 70]
80
60
70
Use of Negative Index
Python3
list = [ 10 , 20 , 30 , 40 , [ 80 , 60 , 70 ]]
print ( list [ - 1 ])
print ( list [ - 1 ][ - 3 ])
print ( list [ - 1 ][ - 2 ])
print ( list [ - 1 ][ - 1 ])
|
Output:
[80, 60, 70]
80
60
70
Method 2: Use of loop to iterate through the list
Python3
list = [[ "Rohan" , 60 ], [ "Aviral" , 21 ],
[ "Harsh" , 30 ], [ "Rahul" , 40 ],
[ "Raj" , 20 ]]
for names in list :
print (names[ 0 ], "is" , names[ 1 ],
"years old." )
|
Output:
Rohan is 60 years old.
Aviral is 21 years old.
Harsh is 30 years old.
Rahul is 40 years old.
Raj is 20 years old.
Use of Temporary Variables inside a loop.
Python3
list = [[ "Rohan" , 60 ], [ "Aviral" , 21 ],
[ "Harsh" , 30 ], [ "Rahul" , 40 ],
[ "Raj" , 20 ]]
for name, age in list :
print (name, "is" ,
age, "years old." )
|
Output:
Rohan is 60 years old.
Aviral is 21 years old.
Harsh is 30 years old.
Rahul is 40 years old.
Raj is 20 years old.
Method 3: Use of Slicing
Python3
list = [ 10 , 20 , 30 , 40 ,
[ 80 , 60 , 70 ]]
print ( list [ 4 ][:])
print ( list [ 4 ][ 0 : 2 ])
|
Output:
[80, 60, 70]
[80, 60]
Please Login to comment...