Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use == and when to use is?

Curiously:

>>> a = 123 >>> b = 123 >>> a is b True >>> a = 123. >>> b = 123. >>> a is b False 

Seems a is b being more or less defined as id(a) == id(b). It is easy to make bugs this way:

basename, ext = os.path.splitext(fname) if ext is '.mp3':     # do something else:     # do something else 

Some fnames unexpectedly ended up in the else block. The fix is simple, we should use ext == '.mp3' instead, but nonetheless if ext is '.mp3' on the surface seems like a nice pythonic way to write this and it's more readable than the "correct" way.

Since strings are immutable, what are the technical details of why it's wrong? When is an identity check better, and when is an equality check better?

like image 478
wim Avatar asked Jul 04 '11 10:07

wim


People also ask

Can you use is instead of ==?

There's a subtle difference between the Python identity operator ( is ) and the equality operator ( == ). Your code can run fine when you use the Python is operator to compare numbers, until it suddenly doesn't.

Is and == mean the same thing?

'is' and '==' operators in Python. The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.

Are the IS operator and == operator the same?

The 'is' is known as the identity operator. 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.

Why is == used instead of?

== is always for testing equality. in most cases used as a drop-in replacement for <- , the assignment operator. used as the separator for key-value pairs used to assign values to arguments in function calls.


2 Answers

They are fundamentally different.

  1. == compares by calling the __eq__ method
  2. is returns true if and only if the two references are to the same object

So in comparision with say Java:

  1. is is the same as == for objects
  2. == is the same as equals for objects
like image 97
Petar Ivanov Avatar answered Oct 11 '22 13:10

Petar Ivanov


As far as I can tell, is checks for object identity equivalence. As there's no compulsory "string interning", two strings that just happen to have the same characters in sequence are, typically, not the same string object.

When you extract a substring from a string (or, really, any subsequence from a sequence), you will end up with two different objects, containing the same value(s).

So, use is when and only when you are comparing object identities. Use == when comparing values.

like image 33
Vatine Avatar answered Oct 11 '22 13:10

Vatine