Using a list of lists in a function


#1



I seems to be printing the right answer?


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



print flatten(n)


#2

no? your output:

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

desired output:

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

you should first create an empty list to which you can append, so you get a flattened list.

the first for loop gives access to the nested lists, so the second for loop should iterate over the iterator of the first fir loop to get the values


#3

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

This?
???

print flatten(n)


#4

okay. but now you also use results as iterator in your for loop? that doesn't work.

your second for loop, why do you loop over lists? look:

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

your second for loop will need to loop over x, so you get access to the items in inner list.


#5

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