16
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?

kojiro
  • 74,557
  • 19
  • 143
  • 201
user2875270
  • 181
  • 1
  • 1
  • 3
  • 6
    Welcome to StackOverflow. Don't worry too much about the downvoters – some people think that every duplicate or beginner question should be downvoted. But besides being a duplicate this is a fine question: it's clear what the question is and it shows pithy code that clearly demonstrates the problem. – kojiro Oct 13 '13 at 03:16

3 Answers3

14

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.

Community
  • 1
  • 1
Tim Peters
  • 67,464
  • 13
  • 126
  • 132
4

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • +1 FWIW, that `id`s are like pointers is an implementation detail specific to CPython. If the Python interpreter is different they might not be. But they'd still be guaranteed to have the same value in this case, even if that value isn't the memory address of the list. – kojiro Oct 13 '13 at 03:06
  • omg thank u i own u my life. also were u the person who downvoted me because if so i will definitely consider retracting the previous statement. – user2875270 Oct 13 '13 at 03:07
  • @user2875270 Nope. I didnt downvote :) This is a beginner question which we all had. So, I just indicated that the question has already been answered in another thread. – thefourtheye Oct 13 '13 at 03:08
  • @kojiro Thats true, that is why included the python doc for `id` in the answer. – thefourtheye Oct 13 '13 at 03:10
3

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)
kindall
  • 178,883
  • 35
  • 278
  • 309