3

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.

Kira
  • 171
  • 1
  • 4
  • 11

4 Answers4

7

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]
miradulo
  • 28,857
  • 6
  • 80
  • 93
3

Objects in python would be considered to be passed by reference. It's a bit different than that, however.

arr = [1, 2, 3]

This statement does two things. First it creates a list object in memory; second it points the "arr" label to this object.

arr1 = arr

This statement creates a new label "arr1" and points it to the same list object pointed to by arr.

Now in your original code you did this:

del arr[:]

This deleted the elements of the list object and now any label pointing to it will point to an empty list. In your second batch of code you did this:

arr = [4, 5, 6]

This created a new list object in memory, and pointed the "arr" label to it. Now you have two list objects in memory, each being pointed to by two different labels. I just checked on my console, and arr points to [4,5,6] and arr1 to [1,2,3].

Here is a good post about it: http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/

2

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).

thebjorn
  • 26,297
  • 11
  • 96
  • 138
-3

You did not do a full copy of the list, instead you just re-assigned the variable name.

In order to make a deep-copy of the list do the following:

arr1 = [x for x in arr]
Sergio
  • 1