Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why operator "is" and "==" are sometimes interchangeable for strings? [duplicate]

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 ?

like image 525
Eduard Florinescu Avatar asked Oct 03 '12 09:10

Eduard Florinescu


People also ask

Can you compare two strings using the == operator in Python?

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.

What is difference between == and is operator in Python?

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.

Why do we use == in Python?

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.

What is == and === in Python?

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.


2 Answers

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.

like image 167
Daniel Roseman Avatar answered Sep 20 '22 13:09

Daniel Roseman


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 :)

like image 32
Morten Jensen Avatar answered Sep 20 '22 13:09

Morten Jensen