jan
jan

Reputation: 1500

Python: different objects get the same id

Looking at the following IPython (Python 3.7) session:

In [1]: id('hello')                                                     
Out[1]: 140300950123104

In [2]: id('hello')                                                     
Out[2]: 140300963300384

In [3]: 'hello' is 'hello'                                              
Out[3]: True

In [4]: '{} - {}'.format(id('hello'), id('hello'))                      
Out[4]: '140300946565808 - 140300946565808'

Expressions 1 and 2 indicate that each time the string hello is initialized, it does get a different id. However, when initialized in the same expression, they seem to get the same id as the results of expressions 3 and 4 suggest. Why is that so?

Upvotes: 3

Views: 1072

Answers (2)

iBug
iBug

Reputation: 37327

This is an interesting question, but it's well explained in wtfpython.

When a and b are set to "hello" in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already hello as an object (because "hello" is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment.

One thing that differs is that in IPython, things might be a bit different from direct Python REPL, so this explains the difference in id in your first two inputs.

Upvotes: 3

VaishaliLambe
VaishaliLambe

Reputation: 19

Two objects with non-overlapping lifetimes may have the same id() value.

Upvotes: 0

Related Questions