Nested loops are loops inside of loops. Now, why would we want loops inside of loops? It's because they help us create advanced functions that we can use to do cool things. We can run
forloops inside of other
forloops. Through these loops, we can develop an elaborate process that can help us sort and analyze data.
Traversing 2D Lists
You can also use nested for loops to traverse 2D (or multi-dimensional) lists:
# Nested Loops # Traversing 2D Lists my_list = [ ["hello", "world", "code"], ["docs", "slides", "sheets"], ["google", "amazon", "facebook"], ["this", "is", "python"], ] # print each element in my_list # and each element in the inner lists for inner_list in my_list: print(inner_list) for word in inner_list: print(word)
View code on GitHub.
Let's step through this code. In the outer for loop, we are iterating through each element in
my_list. Well, each element in
my_listis a list itself. So, when we print
inner_list, it'll print the current
inner_list. Before it moves on to the next inner list, the inner for loop will iterate through each element in the inner list and print it.
['docs', 'slides', 'sheets'] docs slides sheets ['google', 'amazon', 'facebook'] google amazon facebook ['this', 'is', 'python'] this is python
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact email@example.com for inquiries.