1

in python, x is y return ture when x and y are the same object

>>> a = "5"
>>> b = "5"
>>>
>>> a is b
True
>>>
>>> c = a + b
>>> c
'55'
>>> d = b + a
>>> d
'55'
>>>
>>> c is d
False
>>>

To what I understand, a and b are two different objects, but why a is b return True and c is d return False?

Even we regard both a and b as string objects with the same content to explain why a is b return true, why c is d return false then?

Pocketlion
  • 35
  • 1
  • 1
    Possible duplicates: http://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none – shaktimaan Aug 29 '14 at 20:56
  • 1
    `a` and `b` are **not** guaranteed to be different objects, because the Python interpreter can, at its option, choose to intern immutable values when read. – Charles Duffy Aug 29 '14 at 20:56
  • 5
    Please stop upvoting duplicates. – simonzack Aug 29 '14 at 20:57
  • I think this is because the interpreter is just string pooling, is this wrong? – Nowayz Aug 29 '14 at 20:57
  • a and b are actually just names referring to the same integer object `5`, what you can also check with `hex(id(a))` and `hex(id(b))` – redevined Aug 29 '14 at 20:59
  • 1
    @Cipher They are both names referring to the same *string* object, but only because the implementation is interning the string object `"5"`. – chepner Aug 29 '14 at 21:00
  • @chepner sorry didn't see the `"` >. – redevined Aug 30 '14 at 01:55

0 Answers0