18. Using a list of lists in a function


#1
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
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]

#2

Hi @eudesmeria,

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

results = []

#3

Because when I put it, nothing works anymore


#4

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)

#5

@eudesmeria,

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.


#6

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!