In Python, what is the difference between == and the is command?

Asked

Viewed 8,927 times

22

I’m confused in the use of two commands, the is and the == that as far as I understood they perform the same thing that is to compare if two objects are equal.

Is there any more performatic?

2 answers

22


No, that’s not true.

The operator == tests equality of values. It tests whether object values match.

The operator is tests the identity of objects, so it needs to be the same object for it to be true. Obviously if it is the same object they will be equivalent in value. You will not find a situation where the is returns True and the == returns False.

Analyze the difference in these codes:

a = [1, 2, 3]
b = a #copia a referência para o objeto
print(b is a) #é o mesmo objeto
print(b == a) #ele possuem o mesmo valor
b = a[:] #copiou o objeto
print(b is a) #são objetos diferentes
print(b == a) #mas os valores são os mesmos
print(1000 is 10**3) #são objetos diferentes
print(1000 == 10**3) #mas o valor é o mesmo
print("a" + "b" + "c" is "abc") #objetos diferentes
print("a" + "b" + "c" == "abc") #valores iguais

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You might be wondering what happened in the last example of string where something that seems to be another object but is the same. There is an optimization that concatenation is turns into string simple. But still they should be different objects. But one thing called interning to save memory and if the language can detect that it is the same value, it points to the same object. This works well when strings are immutable, case of Python.

  • (There are cases of == being false, with the is True yes - although they are an exception, and in general they are not useful - see below)

  • @jsbueno de facto, has this corner case :) I won’t change the answer because I think for the proper case it is correct, it is the caveat that some crazy person can actually make it happen.

  • Thank you very much!

9

To complement Maniero’s response - the is only compares if the objects are the same. O == compare if they are the same. A lot of people fall into the use trap is to compare strings - but sometimes, due to internal Python optimizations, string trunks were the same object at one time - and another (string larger, file-readable, etc...), to be distinct objects.

So even if in prompt interactive is come back True for two equal strings, never use this when programming. The same goes for integer numbers. In particular, Python automatically creates an instance of each number from 0 to 255 when starting - and the comparison with is of those numbers always returns True - but again, this is just a detail of implementation.

Now - in practical terms, when you define a class, you can determine the behavior of ==. By default, for any new class, the comparison == only returns true if you are dealing with the same object:

In [13]: class A:
    ...:     pass
    ...: 

In [14]: a = b = A()

In [15]: a == b
Out[15]: True

In [16]: c = A()

In [17]: a == c
Out[17]: False

But if your class defines the special method __eq__, it takes as parameters the object itself (self) and the object with which it is being compared - in this case, you determine equality for your own objects. (Already the behavior of is cannot be customized).

In [18]: class B:
    ...:     value = 0  # Atributo de classe
    ...:     def __eq__(self, other):
    ...:         if hasattr(other, "value"):
    ...:             return self.value == other.value
    ...:         return self.value == other
    ...:     

In [19]: d = B()

In [20]: e = B()

In [21]: d == e
Out[21]: True

In [22]: e.value = 5  # sobrescreve value com um atributo para esta instância

In [23]: d == e
Out[23]: False

It is even possible situations where the is returns True and the == False yes - just the method __eq__ return False. In general it is not very useful, but it is used by the special floating point value Nan (Not a number)

In [24]: a = float("Nan")

In [25]: b = a

In [26]: b is a
Out[26]: True

In [27]: b == a
Out[27]: False

In [28]: a == a
Out[28]: False

Browser other questions tagged

You are not signed in. Login or sign up in order to post.