For lists in list


#1

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

def flatten(lists):
    for lst in lists:
        for item in lst:
            print item
    
print flatten(n)

Returns correct output but codeacademy throws following error:
Oops, try again. flatten([[1, 2], [3, 4]]) returned None, did you remember to return the result?
Many thanks in advance for your help.


#2

i would append the items to a new list, given you have to return the result (returning means you have to use the return keyword. And a function ends the moment a return keyword is reached, so create an empty list, append the items, then in the end return the list


#3

Before

you should create an empty list here that hold your results. Say

results = []

Then, after

you will want to append item to result, say

results.append(item)

Also, you will want to return results of the first for loop. Watch your indentation.

I hope this helps! :slight_smile:


#4

Many thanks to both of you. This is my amended code. Gets perfect output but the codecademy is throwing the following error: Oops, try again. flatten([[1, 2], [3, 4]]) returned [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4] instead of [1, 2, 3, 4]

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

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

#5

it seem the checking script only calls the function, place results = [] inside the function. If you don't, the checking script calls the function multiply times, and the list doesn't get cleared each time


#6

Many thanks for your help. I think it is best to draw a box and arrow diagram when dealing with multiple loops. Just we get lazy.


#7

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