Why I can't keep the return just before abc.append() to run the code?

Why it returns NONE in the 1st code but gives value in 2nd code. Why I can’t keep the return just before abc.append() ???

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

print(append_sum([1, 1, 2]))
 
def append_sum(abc):
  abc.append(abc[-2] + abc[-1])
  abc.append(abc[-2] + abc[-1])
  abc.append(abc[-2] + abc[-1])
  return abc

print(append_sum([1, 1, 2]))

because in the first code you are returning the return value of abc.append(abc[-2] + abc[-1]) and this method has no return value so it will return None by default.

Also, try to print it to see what it returns
print(abc.append(abc[-2] + abc[-1])) #prints None

so this line return abc.append(abc[-2] + abc[-1]) will evaluate to return None

2 Likes

The function returns what we told it to return, so if we told it to return 3 it will return 3 every time we call it(). and if we told it to return abc like in the second code it will give us abc when we call it().

And if we told it to return abc.append(abc[-2] + abc[-1]) it will see first what is the value of abc.append(abc[-2] + abc[-1] which is None because this method returns nothing so our function will return this value None.

1 Like