-1

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?

Victor Luu
  • 244
  • 2
  • 10
  • `arr.pop()` is a method of the list object and modifies the object. `arr = ...` assigns a new value to a local variable. – deceze Aug 30 '20 at 15:02

1 Answers1

0

The command arr = arr[:-1] (asssignment to local parameter) needs to be changed to arr[:] = arr[:-1] (assignment to array indexes) in order to change the array.

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22