18. Using a list of lists in a function



This is the error message: "Oops, try again. flatten([[1, 2], [3, 4]]) returned [0, 1] instead of [1, 2, 3, 4]"
I've searched around here for answers but I'm still stuck. Could anybody please help?

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
    results = []
    for numbers in range(len(lists)):
    return results

print flatten(n)


It would seem that the answer is in your code, you will need to observe what it is doing differently from what you want, identify which parts do something different from what you imagine.

If you haven't got it thought out in detail, you'll have to start with that so that you have something to compare to.

The error message you got, see that it says your function returns a list containing a zero? That wasn't in the input list, so where could it possibly be getting that from?


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

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

In this example above, we can see a rule

for A in list_of_lists:
    for a in A:
        print a

There are two 'for loop' to print each number in list_of_list
You can use it to solve your problem.

 def flatten (x):
     results =  [ ]
     for A in x:
         for a in A:
     return results

print flatten(n)


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