0

Why the python shows ambiguous results for is keyword when used against string datatype? Following code snippet describes my question

>>> l1='shrey'
>>> l2='shrey'
>>> l1 is l2
True
>>> l1='shrey saraswat'
>>> l2='shrey saraswat'
>>> l1 is l2
False

Shouldn't it be same at both place? Either True and True or False and False

This question looks similar to 'is' operator behaves differently when comparing strings with spaces . But i wasn't able to find the exact answer there. I just want to know the why and how scenario for the case discussed above.

Community
  • 1
  • 1
Shrey
  • 1,242
  • 1
  • 13
  • 27
  • the question you mentioned has answers that compare is with ==. But i want to know the why and how scenario here – Shrey Nov 18 '14 at 07:05
  • 1
    I think that the answer on the dupe spells it out pretty clearly -- Under certain circumstances the strings are interned -- Cpython doesn't duplicate the string, it actually just stores multiple references to the same string. This is for efficiency as much as anything else and is an implementation detail of Cpython -- Don't expect other implementations (or future versions of Cpython!) to behave the same -- Which is why the advice is to use `==` rather than `is` as the python developers intended :-) – mgilson Nov 18 '14 at 07:14
  • OK Then it means for python "xxx xxx" are two(if not three) different strings. Please correct me if i am wrong here – Shrey Nov 18 '14 at 07:21
  • 1
    In CPython, the `is` operator returns `True` if (and only if) the two objects share the same address in memory. So, if I write `a = 'foo'; b = 'foo'` the expression `a is b` will return `True` if python decides to make `a` and `b` references to the same chunk of memory (that represents the string `'foo'`). Python is allowed to make that optimization if it decides that it can, but _it doesn't have to_. In some cases, python will use that optimization, in others it won't bother. Sometimes `a is b` will be True and sometimes False, depending on the strings or other factors... – mgilson Nov 18 '14 at 07:50
  • Thanks a ton. Good support for a duplicate question :) – Shrey Nov 18 '14 at 10:54

0 Answers0