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


I'm confused by the use of two commands, the is and the == , that as far as I understand they do the same thing that is to compare if two objects are equal.

Is there any more performance?

asked by anonymous 29.12.2016 / 01:19

2 answers


No, this is not true.

The == operator tests equality of values. It tests if the values of objects are equivalent.

The is operator tests the identity of the objects, so it must be the same object for it to be true. Obviously if it is the same object they will equal in value. You will not find a situation where is returns True and == 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

See running on ideoene and on CodingGround .

You may be thinking of what happened in the last string example where something looks like another object, but is the same. There is an optimization that concatenation is transformed into simple string . But they should still be different objects. But a 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 fine when strings are immutable in case of Python.

29.12.2016 / 01:40

To complement the bigown response - is only compares if the objects are the same. The == compares if they are the same. Many people fall into the habit of using is to compare strings - but sometimes, due to internal optimizations of Python, string of strings being the same object on one occasion - and another (larger string, read from file, etc ...), are different objects.

So, even though at the interactive prompt the is returns True for two equal strings, never use this when programming. The same goes for whole numbers. In particular, Python automatically creates an instance of each number from 0 to 255 when it starts - and the comparison with is of these numbers always returns True - but again, this is only 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 receives as parameters the object itself and the object with which it is being compared - in this case you determine equality for your own objects. (The behavior of is can not 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 for situations where is returns True and == False yes - only the __eq__ method returns False. In general it is not very useful, but it is used by the special value of floating point 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
29.12.2016 / 19:47