Consider two simple functions below for taking the last item out of a list:
def pop(arr):
return arr.pop()
def my_pop(arr):
last = arr[-1]
arr = arr[:-1] # update the array
return last
Let a = list(range(10))
.
Using the first method and printing out [pop(a) for i in range(3)]
, I got [9,8,7] and a
is changed as expected. But if I use second method, I got [9,9,9] and a
is not changed at all. What cause these differences?
I guess somehow this is due to the fact that assignment in Python is via pointer. Is that correct? Also, is there a rule of thumb on how updates of an argument are propagated to outside a function?