0

I have a some code:

first = ['a','b']
second = first
second.append('c')
print('Test results: ',first == second, first is second)

Which returns Test results: True True. I expected to get False False. I thought that because the second.append('c') by appending the 'c', the two variables stores different objects - meaning first = ['a','b'] and second = ['a','b','c']

Why do I get True True?

ASm
  • 379
  • 4
  • 10
  • 20
  • You want `second = first[:]` as a copy. – squiguy Jun 03 '15 at 04:04
  • possible duplicate of [How to clone or copy a list in Python?](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python) – squiguy Jun 03 '15 at 04:08
  • @squiguy Thanks for the suggestion, however I'm not looking to modify my code, I'm just trying to get some understanding on the whole reference equality thing. – ASm Jun 03 '15 at 04:09

3 Answers3

3

Because second = first does not make a copy. It makes second and first two references to the same object.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

Actually the issue is in second = first, after execution of this statement, there is no new variable or reference created to some other object instead second is pointing exactly to the same memory location as first. So any changes made in the second would ultimately reflected in the first as well:

first = [1, 2, 3]
second = first
print second
>>> [1, 2, 3]

second.append(4)
print second
>>> [1, 2, 3, 4]

print first
>>> [1, 2, 3, 4]

To avoid such issues you deepcopy to initialize a new list.

from copy import deepcopy
a = [1, 2, 3]
b = deepcopy(a)
b.append(4)
print b
>>> 1, 2, 3, 4
print a
>>> 1, 2, 3
ZdaR
  • 22,343
  • 7
  • 66
  • 87
0

Option # 1 - here references are being compared instead the values

first = ['a','b']
second = first
second.append('c')
print('Test results: ',first == second, first is second)
## >> result :  it will always return TRUE

Here I recommend to use first is second for individual array element than on whole array though Python wont stop you from doing that.

Option # 2 - its more appropriate way

print cmp(second, first)
## >> result : it will return 0 i.e. False

Option # 3 - make use of numpy array

print np.array_equal(first, second)
## >> result : it will return False too.

You can also use deepcopy as explained by ZdaR in the answer above.

Pralhad Narsinh Sonar
  • 1,406
  • 1
  • 14
  • 23