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?
Check if two arrays are equal or not using Sorting Follow the steps below to solve the problem using this approach: Sort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.
Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With