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 :
![Rendered by QuickLaTeX.com list=[10, 20, 30, 40, [ 80,60, 70 ] ]](https://web.archive.org/web/20240118164513im_/https://www.geeksforgeeks.org/wp-content/ql-cache/quicklatex.com-262edd8187fe178ada23c5e6df0a2d7e_l3.png)

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]
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
08 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...