18 Using a list of lists in a function


#1



This is the error message in the console:
Traceback (most recent call last):
File "python", line 12, in
File "python", line 6, in flatten
NameError: global name 'numbers' is not defined


I'm not terribly sure where I'm going wrong. It has to be with the iterations, I'm guessing.
Have tried different combinations. And getting similar error.

I understand what we're trying to do, or at least, I think I do.
Thanks for any help! :slight_smile:


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

print flatten(n)


#2

so if you have this loop:

for n in lists:
   print n

you will get access to the inner list, the above code would output:

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

so if would then loop over n (not numbers) we would get access to the numbers in the list (which then will be in i) so we can append them to results.

also, append() will update results, so you don't have to do that


#3

Aha! Forgot append() updates. That helped some...

Got it, thank you :slight_smile: Think I was very much trying to over-complicate, plus I was thinking about it all in the least sensible way!


#4