Home > other >  python array reference not removing element from the array
python array reference not removing element from the array

Time:01-16

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 !

CodePudding user response:

As I've already pointed in this comment, if you need in-place list modification, you can apply slice notation:

def check(arr):
    arr.append(1)
    arr[:] = arr[:-1]

But in fact this code will just remove last item (which you have added one line above), so you can just use del:

def check(arr):
    arr.append(1)
    del arr[-1]

CodePudding user response:

Alternatively it can be done with a global variable:

def check_arr():
    global arr
    arr.append(1)
    arr = arr[:-1]

arr = [1]
check_arr()
print(arr)

CodePudding user response:

You don't return anything. The arr in the function is in local scope, so the global scope arr won't update

def check(arr):
    arr.append(1)
    return arr[:-1]

arr = [1]
arr = check(arr)
print(arr)
  •  Tags:  
  • Related