Appending a list as a function - incorrect use of return

Hello, I’m wondering why this line of code runs

def append_sum(lst):
  lst.append(lst[-1] + lst[-2])
  lst.append(lst[-1] + lst[-2])
  lst.append(lst[-1] + lst[-2])
  return lst

but my one does not:

 def append_sum(lst):
   lst.append(lst[-1] + lst[-2])
   return lst
   lst.append(lst[-1] + lst[-2])
   return lst
   lst.append(lst[-1] + lst[-2])
   return lst

I realise the first is far less clunky, but do not see why mine does not run. Could someone please explain why my use of return is wrong, am I not understanding the purpose of it?

You are returning the list each time you append an element.

According to GeeksForGeeks:

A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.

So, return is designed to “give back” (return) the result of the function; in this case, the fully modified list.

2 Likes