How do nested loops work?


#1

Question

How do nested loops work?

Answer

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.

  1. My list_of_lists is just a list with 2 lists nested inside of it.
  2. I create a function called reset_list_items() that takes some nested list as an argument, called nested_list.
    .3. zeros_resultwill store all my zeroed out values. There should be one0for every number present in the given nested list, so 60`s total in the code above, all in one, single list at the end.
  3. My outer loop loops one time for every_list present in the nested_list. So in this case, the outer loop runs two times total because list_of_lists is made up of 2 inner lists.
  4. My inner loop loops one time for every item present in 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.
  5. Each time my inner loop runs it appends a 0 to my zeros_result list.
  6. I return my zeros_result outside of my loops, on the same indentation level as the outer for loop so that it is not inside of the loops.
  7. The printed result is: [0, 0, 0, 0, 0, 0], we did it!

FAQ: Learn Python - Lists and Functions - Using a list of lists in a function
FAQ: Learn Python - Lists and Functions - Using a list of lists in a function
#2

I think an important point missed in the exercise instruction is that to combine the lists, we are actually making a new one by adding all variables to a blank list, instead of actually adding them together.