array1=[0,1,2]
array2=array1
array2[0]=234234
print array1
OUTPUT:
[234234, 1, 2]
Why does python change 'array1'? Shouldn't it just change array2? How can I prevent python from changing array1 when I change array2?
array1=[0,1,2]
array2=array1
array2[0]=234234
print array1
OUTPUT:
[234234, 1, 2]
Why does python change 'array1'? Shouldn't it just change array2? How can I prevent python from changing array1 when I change array2?
array1
and array2
are the same object. That's why changing either changes the other. If you want to copy the object, here's one way to do it:
array2 = array1[:]
See more on this here.
Use slice notation to copy like this
array2 = array1[:]
Or you can use list
function
array2 = list(array1)
When you assign one list to another list, a new list will not be created but both the variables will be made to refer the same list. This can be confirmed with this program.
array1 = [1, 2, 3, 4]
array2 = array1
print id(array1), id(array2)
They both will print the same id. It means that they both are the same (If you are from C background you can think of them as pointers (In CPython implementation they really are pointers, other implementations choose to print unique ids - Please check kojiro's comment)). Read more about id
here. When you do
array3 = array1[:]
array4 = list(array1)
print id(array1), id(array3), id(array4)
you ll get different ids, because new lists will be created in these cases.
array1
and array2
are two names for the same list, since that's how you set them. If you don't want this, copy the list using one of the following methods:
array2 = array1[:]
array2 = list(array1)