How do nested loops work?

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!
16 Likes

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.

13 Likes

TY! I had no clue what to do until I saw this.

Greetings.

Is there a way to do it using the “for i in range(len(list)):” method? I’m trying to figure out how that would work logically.

range produces a list:

print range(5)

The values from this list, you use as indices to get values from a list:

my_list = ['a', 'b', 'c']
for index in range(len(my_list)):
   print index, my_list['index']

indices are really useful when having to manipulate a list:

my_list = [4, 6, 8]
for index in range(len(my_list)):
   my_list[index] += 3
print my_list

given in this exercise you don’t need to update values in the list, range would only complicate things

2 Likes

Thank you so much for providing us with this step-by-step breakdown of how nested lists work. I love the codeacademy learning community.

1 Like

All was correct except for the placement of my ‘return’. After correctly indenting this text, the function output the correct answer.

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
  results = []
  for numbers in range(len(lists)):
    for number in range(len(lists[numbers])):
      results.append((lists[numbers])[number])
  return results
print flatten(n)

Btw no matter what method you use, the n[] must contain only lists, not a mix of lists and integers.

1 Like

No, you can check if you are dealing with a list or not with type():

def flatten(lists):
  results = []
  for numbers in range(len(lists)):      
      if not type(lists[numbers]) == list:
          results.append(lists[numbers])
      else:
          for number in range(len(lists[numbers])):
              results.append((lists[numbers])[number])
  return results

n = [[1, 2, 3], 13, [4, 5, 6, 7, 8, 9], ['xyz', 'abc']]
print(flatten(n))

Output:

[1, 2, 3, 13, 4, 5, 6, 7, 8, 9, 'xyz', 'abc']
3 Likes

I’ve never thought about checking what is in [numbers] before appending its content. Thanks!
In light of your codes, I wrote below for “for item in list” method:

def flatten(lists):
  results = []
  for numbers in lists:
    if not type(numbers) == list:
      results.append(numbers)
    else:
      for number in numbers:
        results.append(number)
  return results

n = [[1, 2, 3], 13, [4, 5, 6, 7, 8, 9], ['xyz', 'abc']]
print flatten(n)
2 Likes

Yes, very Pythonic to avoid indexing when it is not necessary!

1 Like

2 posts were split to a new topic: Why is this one wrong?