List of list in a function


#1

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

Error: flatten([[1, 2], [3, 4]]) returned [1, 2, 3, 4, 5, 6, 7, 8, 9] instead of [1, 2, 3, 4]

What is the mistake here?


#2

you loop over n. Look:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# function declaration
def flatten(lists):
   print lists

# function call
flatten(n)

at the function call i supply n as argument, so then we have access to the list thanks to the function parameter (lists)

the advantage of this method is that your function works for multiply lists instead of one. (just pass a different list as argument when calling the function)

The exercise calls the function multiply times with different lists, for validation purposes, that is why you get the error.


#3

Thank you very much.


#4

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