I was adding and removing elements to an array reference within a method, and i found that though the elements were getting added to the array in reference but it was not getting removed.
def check(arr):
arr.append(1)
arr = arr[:-1]
arr = [1]
check(arr)
print(arr)
gives the output [1, 1] I want to know why arr = arr[:-1] not removing from the referenced array
EDIT: a lot of people are posting the correct solution, I am not looking for a solution, instead an explanation of why and how python creates a local variable instead of overwriting the global scope and how does it maintain the two by the same name !
arr = arr[:-1]This creates a new local variable namedarr. It does not affect the original argument.arr[:] = arr[:-1]or (for this particular case)del arr[-1]arraybut alist. Those two are different.