Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays in Python are assigned by value or by reference?

Tags:

python

arrays

I am wondering why when I delete the original array it affects the copied array:

arr = [1,2,3]
arr1 = arr
del arr[:]
print(arr1) #this prints []

but when I modify the elements of the original array there is no effect on the copied array:

arr = [1,2,3]
arr1 = arr
arr = [4,5,6]
print(arr1) #this prints [1,2,3]

If someone can explain this issue I appreciate your help, thanks in advance.

like image 919
Kira Avatar asked May 03 '26 01:05

Kira


2 Answers

You did not modify the elements of the original array, but rather re-assigned a new list to the arr variable. Your intuition of thinking changes to elements would be reflected in arr1 if you properly accessed its elements is indeed true as lists are mutable in Python. For instance,

arr = [1,2,3]
arr1 = arr
arr[1] = 4
print(arr1) #this prints [1,4,3]
like image 130
miradulo Avatar answered May 04 '26 14:05

miradulo


There are several ways to copy an array, but

arr1 = arr

is not one of them (in C-speak, that is just an aliased pointer). Try one of

arr1 = arr[:]  # slice that includes all elements, i.e. a shallow copy
arr1 = copy.copy(arr)  # from the copy module, does a shallow copy
arr1 = copy.deepcopy(arr)  # you guessed it.. ;-)

after any of those you will see that changes to arr1 and arr are independent (of course if you're using a shallow copy then the items in the list will be shared).

like image 32
thebjorn Avatar answered May 04 '26 16:05

thebjorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!