0

Take the following simple code.

a = "first"
b = "first"

print(id(a))
print(id(b))

id(a) is the same as id(b)

I am aware of the stack and heap situation. However, very unclear how does Python know that we have the same string here. I would expect python to create two objects in the heap. "a" would reference to one object and "b" would reference to another object.

kfcnhl
  • 1
  • 2
  • 1
    https://stackoverflow.com/q/15541404/3001761 – jonrsharpe May 02 '22 at 20:50
  • 1
    It doesn't, really. It only reports the ID value associated with the *object* referenced by the two variables. – chepner May 02 '22 at 20:52
  • 2
    It's an implementation detail of your interpreter (an internal cache) that the literal `"first"` reuses the same object for `b` that it used for `a`. – chepner May 02 '22 at 20:52
  • With `b = "first".lower()` or `b = "afirst"[1:]` you get different ids (at least with Python 3.9.1). Looks like compile time optimization. – Matthias May 02 '22 at 20:55
  • "I am aware of the stack and heap situation." what do you mean by this? – juanpa.arrivillaga May 02 '22 at 20:56
  • 1
    " I would expect python to create two objects in the heap. "a" would reference to one object and "b" would reference to another object." Python, the language, is free to handle immutable objects differently. It so *happens* (as an implementation detail that should never be relied on) that when a code block is compiled, immutable literals will all refer to the same object in that code block. – juanpa.arrivillaga May 02 '22 at 20:58

0 Answers0