How do nested loops work?
Nested loops are tricky, even if you’ve worked with loops before. Particularly difficult is keeping track of each
for loop variable, so it may help if you work out the example below on paper, step by step.
In this example I’m going to change the value of each list item to
0 and my function will be given a list of lists, just like in this exercise.
list_of_lists = [ [1, 2, 3], [4, 5, 6] ] def reset_list_items(nested_list): zeros_result =  for each_list in nested_list: for item in each_list: zeros_result.append(0) return zeros_result print reset_list_items(list_of_lists)
Now we can take a closer look at what’s going on above.
list_of_listsis just a list with 2 lists nested inside of it.
- I create a function called
reset_list_items()that takes some nested list as an argument, called
will store all my zeroed out values. There should be one0
for every number present in the given nested list, so 60`s total in the code above, all in one, single list at the end.
- My outer loop loops one time
every_listpresent in the
nested_list. So in this case, the outer loop runs two times total because
list_of_listsis made up of 2 inner lists.
- My inner loop loops one time
each_list, which we know is each nested list in the initial list. So it loops 3 times over
[1, 2, 3]and then returns to the outer loop, and then 3 times over
[4, 5, 6]and then returns to the outer loop where there’s nothing left to do.
- Each time my inner loop runs it appends a
zeros_resultoutside of my loops, on the same indentation level as the outer
forloop so that it is not inside of the loops.
[0, 0, 0, 0, 0, 0], we did it!