Possible Duplicate:
String comparison in Python: is vs. ==
Python string interning
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
I used accidentally is
and ==
for strings interchangeably, but I discovered is not always the same.
>>> Folder = "locales/"
>>> Folder2 = "locales/"
>>> Folder is Folder2
False
>>> Folder == Folder2
True
>>> File = "file"
>>> File2 = "file"
>>> File is File2
True
>>> File == File2
True
>>>
Why in one case operators are interchangeable and in the other not ?
Python comparison operators To compare two strings, we mean that we want to identify whether the two strings are equivalent to each other or not, or perhaps which string should be greater or smaller than the other. This is done using the following operators: == : This checks whether two strings are equal.
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory.
The == operator helps us compare the equality of objects. The is operator helps us check whether different variables point towards a similar object in the memory. We use the == operator in Python when the values of both the operands are very much equal.
The == operator checks to see if two operands are equal by value. The === operator checks to see if two operands are equal by datatype and value.
Short strings are interned for efficiency, so will refer to the same object therefore is
will be true.
This is an implementation detail in CPython, and is absolutely not to be relied on.
This question sheds more light on it: String comparison in Python: is vs. ==
The short answer is: ==
tests for equal value where is
tests for equal identity (via object reference).
The fact that 2 strings with equal value have equal identity suggests the python interpreter is optimizing, as Daniel Roseman confirms :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With