+ 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?
2 odpowiedzi
+ 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:)
+ 3
With return lst.append(len(lst)) you return the return value of the method append() which is None.