I’m learning Python 3 through Codecademy and am struggling to understand the difference between these bits of code:
def append_size(lst):
lst.append(len(lst))
return lst
vs
def append_size(lst):
return lst.append(len(lst))
Both functions are called with print(append_size([23, 42, 108])
Why does the first work (prints [23, 42, 108, 3]) and the second returns ‘None’?
>Solution :
Okay so the append function is used to add an item to an existing list.
Suppose I have a list a = [1,2,3] and I want to add 4 to the list. I’ll do a.append(4) and would get the desired output of [1,2,3,4].
In the first append_size function the code firstly appends an item to the original list and then returns the list that’s why you get a list output of [23, 42, 108, 3]. But in the second function the code returns lst.append and not any list. Because the append function always has the value None, it returned None as the output.