Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting two arrays equal [duplicate]

Tags:

python

arrays

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?

like image 422
user2875270 Avatar asked Oct 13 '13 02:10

user2875270


People also ask

How do you equalize two arrays?

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.

Can you set two arrays equal to each other?

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.


3 Answers

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.

like image 59
Tim Peters Avatar answered Oct 18 '22 02:10

Tim Peters


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.

like image 4
thefourtheye Avatar answered Oct 18 '22 02:10

thefourtheye


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)
like image 3
kindall Avatar answered Oct 18 '22 02:10

kindall