6

In the following python script, why the second assert goes through (i.e., when adding 0 to 257 and stores the result in y, then x and y become different objects)? Thanks!

x = 257
y = 257
assert x is y

x = 257            
y = 257 + 0
assert x is not y
Farrousa
  • 149
  • 1
  • 11
  • do not use `is` to check for equality ... basically ever ... it is litterally the memory location variable ... python prestores a small number of constants that will just happen to work in some cases ... – Joran Beasley Jul 05 '16 at 20:38
  • Check this answer out; it explains why `is` seems to work strangely sometimes! http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python – Peter Wang Jul 05 '16 at 20:39

2 Answers2

2

integers are non mutable so any operation to change them results in a new memory location

>>> a =9876
>>> id(a)
38478552
>>> a+=1
>>> id(a)
38478576
>>> a+=0
>>> id(a)
38478528

is is checking the actual memory location of the object ... and should basically never be used to check for value equality (although it may arbitrarily work on some small subset of cases)

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

When you use is, you are checking whether or not the two objects point to the same memory location. If they do, then the result is True. Otherwise, the result is False.

To check if the values are equivalent, use ==, e.g. assert x == y. Alternatively, to assert that they are not equal, use !=, e.g. assert x != y.

x = 257
y = 257


>>> id(x)
4576991320

>>> id(y)
4542900688

>>> x is y
False

x = 257
y = 257 + 0

>>> id(x)
4576991368

>>> id(y)
4576991536
Alexander
  • 105,104
  • 32
  • 201
  • 196