Can someone just break down what is happening here?


#1

Why do you iterate through numbers in lists and number in numbers? I really don’t understand the logic here at all.

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

def flatten(lists):
  results = []
  for numbers in lists:
    for number in numbers:
      results.append(number)
  return results

print flatten(n)
#prints [1, 2, 3, 4, 5, 6, 7, 8, 9]

Also the example for the code below says, “We iterate through our outer list.
For each of the two inner lists (as lst), we iterate through the numbers (as item) and print them out.”

What does it mean by inner and outer lists? There are only 2.

list_of_lists = [[1, 2, 3], [4, 5, 6]]

for lst in list_of_lists:
  for item in lst:
    print item

#2

maybe add some print statement to see what is happening?

well, this function coverts a 2d list into a 1d list.

So we need to loop over the 2d list to get to the inner list, then a loop to loop over the inner list, and append to result. This will cause a new list which is 1d

1d or 2d = x dimensional.


#3

Yea I forgot just added it


#4

I had edited to ask but what do you mean by inner and outer list? Would the inner list be 1,2,3 and the outer be 4, 5, 6, 7, 8, 9?


#5

no, both this lists are inner lists, they are nested within the outer list (the outer most [])


#6

Ok I think I got it Thanks!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.