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
for loops inside of other
for loops. 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:
# 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_list is 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