2

Integers and Strings are immutable types that can safely be compared for identity.

x = 12
x is 12
>>> True
x = "twelve"
x is "twelve"
>>> True

Since the is operator is comparing memory addresses, this means that Python essentially considers x to be the same as 12 and then the same as "twelve". This means you can opt to use is to test them rather than the equality operator.

However, I just found out that there's only a specific range where this actually works for integers.

x = 256
x is 256
>>> True
x = 257
x is 257
>>> False
x = -5
x is -5
>>> True
x = -6
x is -6
>>> False
id(x)
>>> 35608408L
id(-6)
>>> 35608864L

This means that identity only actually works for -6 < x < 257. Is there such a limit for strings too that would make identity comparisons unreliable after a certain length? Also is this specific to Python 2.7 or subject to any other variations?

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
  • 2
    Never assume that a literal will produce the same object more than once. The fact that the interpreter *may* do this is an optimization, not a language guarantee. – chepner Aug 25 '15 at 16:52
  • 1
    Read the second answer in the duplicate – jonrsharpe Aug 25 '15 at 16:56

0 Answers0