Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: different objects get the same id [duplicate]

Tags:

python

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?

like image 754
jan Avatar asked Sep 22 '26 19:09

jan


1 Answers

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.

like image 105
iBug Avatar answered Sep 25 '26 09:09

iBug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!