return a list in python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

return a list in python

My question is : write a function that adds the length of the list to the list My solution: def add_list(lst): return lst.append(len(lst)) print (add_list([2,1, 3])) and it returns None but def add_list(lst): lst.append(len(lst)) return lst print (add_list([2,1, 3])) gives me the right answer : [3, 2, 1, 3] It seems these two functions are identical but why they have different behavior?

17th May 2020, 8:19 PM
Sagheb
Sagheb - avatar
2 Answers
+ 4
lst.append will update lst directly... The return value of append is None. that's why in your first example the returned value is just that - None... in your second example you added another step, so the result is just as you expected it:)
17th May 2020, 8:33 PM
G B
G B - avatar
+ 3
With return lst.append(len(lst)) you return the return value of the method append() which is None.
17th May 2020, 8:37 PM
Jnn
Jnn - avatar