0

I'm using Python 3.8.10 and I don't get why the ids are different in the following example.

In this case, the ids are the same.

>>> a = "latter"
>>> b = "latter"
>>> a is b
True

>>> id(a)
139821162817136
>>> id(b)
139821162817136

However, if I add an ':', the two strings have different ids.

>>> a = "latter:"
>>> b = "latter:"
>>> a is b
False
>>> id(a)
139821163527280
>>> id(b)
139821162817200

I don't get what exactly is happening.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Devang Hingu
  • 578
  • 1
  • 6
  • 20
  • 1
    Duplicate here? https://stackoverflow.com/questions/24245324/about-the-changing-id-of-an-immutable-string – jprebys Jun 22 '22 at 13:52
  • 2
    The strings are the same; the `str` objects are different. String interning is implementation-specific and cannot be relied upon. – chepner Jun 22 '22 at 13:57
  • @jprebys: ['is' operator behaves differently when comparing strings with spaces](https://stackoverflow.com/q/16756699/364696) is a better dupe target; it covers why some string literals get interned while others don't (specifically in terms of a CPython implementation detail on when string literals are interned), while [About the changing id of an immutable string](https://stackoverflow.com/q/24245324/364696) is asking about interning in general (it never addresses what *breaks* the automatic interning; the OP never tried non-variable name characters). – ShadowRanger Jun 22 '22 at 13:59
  • My understanding is that CPython will *not* intern strings over a certain length, and *might* intern shorter strings. Trying to predict which strings will be interned and relying on that prediction is an exercise in futility. The *only* time you can safely rely on `a is b` being true is if the value of one variable is by assignment the value of the other (i.e., `a = b` or `b = a`). – chepner Jun 22 '22 at 14:02

0 Answers0