2

When I compare id of a and b as following it returns true

a = 5
b = 5
print(a is b) # prints true 

a = 5
b = 4
b += 1
print(a is b) # prints true 

but when I use do the same thing with the string it returns false

s1 = 'string'
s2 = 'strin'
s2 += 'g'
print(s1 is s2) # returns false
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Sahil Lohiya
  • 154
  • 2
  • 11
  • 5
    Because interning is implementation-defined and you shouldn't rely on it. It's just an optimization and up to the implementation what is interned. – Mark Tolonen Dec 04 '22 at 19:52
  • 1
    Why would they be the same? For the `int` case, for example, this is the corollary of the small-int cache, since 5 falls into the small int range. – juanpa.arrivillaga Dec 04 '22 at 19:57
  • 1
    https://python-tutorials.in/python-is-operator/ See especially the summary at the bottom describing usage of `is` vs. `==`. – Erik Eidt Dec 04 '22 at 19:58
  • 2
    CPython interns 260 or so `int` values. That's less by several orders of magnitude than even the number of single-character `str` values. See https://stackoverflow.com/questions/35805768/what-are-the-rules-for-cpythons-string-interning. – chepner Dec 04 '22 at 20:03
  • 3
    Interning requires the implementation, *every* time a new value is created, to check if the value was already created. Most interning decisions are based on the question of when is creating a new value less expensive than the overhead of finding an existing value. – chepner Dec 04 '22 at 20:04
  • as far as I understood, it depends on the implementation of python whether or not to intern or not and these values. and implementation decisions are made considering tradeoff of the time and memory. – Sahil Lohiya Dec 05 '22 at 07:13

0 Answers0