18/18


#1

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:
      results.append(x)
      return results
      
print flatten(n)

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


#2

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?


#3

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?


#4

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


#5

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.


#6

Awesome that worked thank you!


#7

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