# 18. Using a list of lists in a function

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

def flatten(lists):

for numbers in lists:
for num in numbers:
results.append(num)

return results

print flatten(n)

Hello, I have a problem about this, I could not understand what is wrong, my code return well:

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

Hi @eudesmeria,

Why is this outside the function, rather than within it?

results = []
2 Likes

Because when I put it, nothing works anymore

Not quite sure why that would be. Especially considering itâ€™s supposed to be within the function. As a matter of fact, it goes right above the for statement. As proof of this, you can try what @appylpye recommends:

While youâ€™re at it, please remove that white-space before your return statementâ€¦

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

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

print flatten(n)
2 Likes

As a test, call your function twice using two different nested lists. Youâ€™ll observe that there is a problem that needs to be corrected by initializing results within the function rather than outside it.

1 Like

Yes, reading problem in order, itâ€™s indicated, actually I just found the sollution by rummaging on google, I was far I will not find, it allows me to understand what it was necessary to do, Thank you for your help!

1 Like