18/18 using a list of lists in a function WONT WORK!


#1

def flatten(lists):
results = []
for n in lists:
for items in n:
results.append(items)
return results
print flatten(n)

WTF I am so sick of this.. Have been tried every suggestion on this exercise. Don't understand why this wont work.


#2

Here try this

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(n):
    s = []
    for i in n:
        s += i
    return s

print flatten(n)

Hang in there buddy


#3

Or

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

#4

Thank you!
Don't know why but it finally worked.


#5

Thanks, but I did need to iterate two 'for' commands.


#6

Hi! here is my code and it worked:

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

Add your function here

def flatten(lists):
(1 indent) results = []
(1 indent) for numbers in lists:
(2 indent) for i in numbers:
(3 indent) results.append(i)
(1 indent) return results

print flatten(n)


#7

@gretchenf @giacat2003

to format your code here you paste it in here, select it and hit ctrl+k or the </> in the tools pane


#8

Hi there I'm going to try to explain @trinityalamo's code.
A function is made called "flatten" which takes the argument "lists". An empty list called "results" is first created, then we make a for loop that iterates through "lists" but we have lists within the list (n). So in order to iterate those lists within the list we make another for loop and append the results to "results". Lastly we "return" the results so we can see them.


#9

Thank you. When I said 'I don't know why' I did not mean I did not understand, which frequently I don't so stay close, but what I don't understand is why the same code will work sometimes but not others.
Can you answer that? Or why the lessons seem to pass you to the next lessons even when the code should not have worked or did not return the results it was supposed to.


#10

You're not alone, this happens to everybody. One of the major cons of this site.