Hey all,

Currently stuck on this problem, I read past forum posts about this, but it looks like my code is right, only difference being variable names. Here is what I have:

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)

Give me the error:
flatten([[1, 2], [3, 4]]) returned [1] instead of [1, 2, 3, 4]


by default a function returns None at the end of the function, so returning is the last thing/final thing a function does

if we want to return something else at the end of the function, we can use the return keyword, thus, when a return keyword is reached, the function ends

Given this insight, what do you think is wrong with your code?


Thank you! So if I’m getting you correctly the return keyword should be closing the main for loop, not the secondary loop, and return the results of the overall function?


to get the flat list, all loops need to make all there iterations, so return should be place outside after the loops have finished running, if that is what you mean, then yes


You should compute the result and then return. By the time you’ve finished computing the result you’ll likely not be inside a loop any more, because the loop is part of the computation, meaning you haven’t got the result yet

return doesn’t interact with loops, there’s nothing special going on there. But it does exit the function.


Awesome that worked thank you!


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