3

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?

Chris Hunt
  • 3,840
  • 3
  • 30
  • 46
jan
  • 1,408
  • 13
  • 19
  • Related: https://stackoverflow.com/questions/36620764/python-different-memory-management-behaviours-when-run-in-python-shell-and-py – Alex Hall Jan 21 '19 at 15:32
  • Possible duplicate: https://stackoverflow.com/questions/24802740/unnamed-python-objects-have-the-same-id – Tarifazo Jan 21 '19 at 15:33

2 Answers2

3

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.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • I can confirm that python behaves differently than ipython: `python -c 'print(id("hello")); print(id("hello"))'` -> `139863431234648 139863431234648` – jan Feb 23 '19 at 13:11
  • If you type `id('hello')` at the REPL, the lifetime of `'hello'` is over immediately which is why it can receive a different id the next time around. When both exist at the same time, it's more efficient to store them in the same memory in which case they get the same id. – Alex W Mar 25 '21 at 17:58
0

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