18/18 Using a list of lists in a function


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

Add your function here

def flatten(lists):
results = []
for numbers in lists:
for x in numbers:
return results

print flatten(n)

flatten([[1, 2], [3, 4]]) returned [1] instead of [1, 2, 3, 4]

why is this not iterating the whole loop?


by default, a function returns at the end, which we can prove:

def example():
    print "function needs to do something"

print example()

i put a print statement in front of the function call, this is to print the returned result. As you can see when running this code, it should say None

we didn’t specify this, but it seems one of python features is to return None at the end of the function.

If we want to return something else at end of the function we can use the return keyword:

def example():
    print "i get executed"
    return True
    print "i won't get executed, given return ends the function"


however, as you can see, the return keyword ended the function, the second print statement is never reached.

So, in your function, return will break the loops, so the function can end. Given that return is the last action a function takes


make sure the return is written with proper indention. it should not be under any of the for loops, instead it should be indented as per def keyword.


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