Need help on appending to a list


#1

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



print flatten(n)

#2

you're iterating through nothing. n is not defined. They ask for you to iterate through lists.

Now that you know that you should iterate through lists, why append n? They ask to append the new number of your second loop to results.


#3

Your function is not using the parameter, for starters. Plus, your code is appending the whole list multiple times.

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

Two corrections:

for lst in lists:

and,

results.append(i)

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

#4

thanks for the help. :slight_smile:


#5

But is it not in global scope?


#6

Just noticed that. Thanks for pointing me out @mtf :slight_smile:


#7

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