1

In python I have experienced something that was a little weird for me.

>>> a = "a"
>>> b = "a"
>>> a is b
True
>>> id(a) == id(b)
True

But when I choos another string value for a and b this behaves different.

>>> a = "dlfkgmdflkgd gdflkg dflkg dflkgd fgdfg"
>>> b = "dlfkgmdflkgd gdflkg dflkg dflkgd fgdfg"
>>> a is b
False
>>> id(a) == id(b)
False

what is the difference betwee "a" and "dlfkgmdflkgd gdflkg dflkg dflkgd fgdfg" ?

Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34
  • There may be something wrong with your interpreter. I just ran it and it worked fine. – Ismail Hafeez Mar 12 '21 at 18:05
  • I tested in an online interpreter and it gave `True`. [Try it online!](https://tio.run/##lY07DoAgEET7PcV0uLU1hwE2IBHRqI2nRzSY0NrML5O87TqnNY@lGGgoo8g2p22P@RwM4gHLrUUZDENr1GCZidzzluTnsIhPcxCE19GpwNcxKJI/50Z0D186vvv4wlzKDQ "Python 3 – Try It Online") – gen_Eric Mar 12 '21 at 18:07
  • it's very strang! – Amir reza Riahi Mar 12 '21 at 18:08
  • 2
    I'm getting the same results as @Amir inside the Command Prompt. – Have a nice day Mar 12 '21 at 18:08
  • It works differently in the Python shell. As @Haveaniceday said, it returns `False` in the Command prompt. – Justin Mar 12 '21 at 18:10
  • 1
    Read about [String Interning](https://medium.com/@bdov_/https-medium-com-bdov-python-objects-part-iii-string-interning-625d3c7319de#c549) – Yevhen Kuzmovych Mar 12 '21 at 18:11
  • This is the result of an optimization in the CPython interpreter. [some more details...](https://stackoverflow.com/q/24245324/3929826) – Klaus D. Mar 12 '21 at 18:12
  • @Justin yes, I've tested the code as a file and get `True`. But in shell I get `False` – Amir reza Riahi Mar 12 '21 at 18:13
  • @AmirrezaRiahi - Try `a == b` – Justin Mar 12 '21 at 18:39
  • 1
    Does this answer your question? [Why does comparing strings using either '==' or 'is' sometimes produce a different result?](https://stackoverflow.com/questions/1504717/why-does-comparing-strings-using-either-or-is-sometimes-produce-a-differe) – Justin Mar 12 '21 at 18:42
  • 1
    This isn't strange. Why do you *think* they should have the same id??? Basically, the python runtime is free to optimize various immutable types. All of these are *implementation details* (that shouldn't be relied on), for example, length-1 strings are interned. You shouldn't rely on this, and it should be *surprising* that these would ever have the same id, not the opposite! – juanpa.arrivillaga Mar 12 '21 at 18:47

0 Answers0