'What is the difference between "is" and "=="? [duplicate]
What is the difference between these two pieces of code in the boolean world:
1 is 1
and
1 == 1
I found two web pages that describe it, but I can't see the difference since I don't know how to get different results:
http://www.informit.com/articles/article.aspx?p=459269&seqNum=10
https://docs.python.org/2/library/stdtypes.html
On the 2nd page, I found the operators. On the 1st page, which I looked at second, it described a difference that doesn't tell me when I'd do this and get different results. That's my big question, is when does doing one differ results from the other?
Obviously, there are cases where one will be true and the other false, right?
Solution 1:[1]
When using variables, it can cause incorrect results:
>>> foo = [1, 2, 3]
>>> foo is [1, 2, 3]
False
>>> foo == [1, 2, 3]
True
Look at the documentation, here
==
means "equal", while is
is an object identity.
Solution 2:[2]
Equality is well-defined, type by type, depending only on the values being compared. Identity depends on whether a certain value is duplicated, or stored only once and referred to repeatedly.
For immutable values, identity's therefore an implementation detail!
Consider, for example:
2>>> x = 23
2>>> y = 23
2>>> x is y
True
2>>> x = 232323
2>>> y = 232323
2>>> x is y
False
Small values like 23
happen to be "cached" (an implementation detail!) in CPython in the hope of saving memory if they're used often; large values like 232323
are not so cached -- again, 100% an implementation detail. You'd never want to depend on such behavior!
Solution 3:[3]
In addition to these, you can change the behavior of ==
for classes that you define.
class A:
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
#let us ignore b in our comparison!
return self.a == other.a
a1 = A(1,2)
a2 = A(1,3)
print(a1 == a2) #prints true
print(a1 is a2) #prints false
The behavior of is
cannot be changed and will always compare the memory addresses where the objects themselves are stored.
Solution 4:[4]
a is b checks if a points to the same memory location as b a == b checks if the values of a and b are the same. e.g.
a=10 (computer stores '10' at 0xf34852)
b=10 (computer stores '10' at 0xfeac54)
a==b (true)
a is b (false)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Zach Gates |
Solution 2 | Alex Martelli |
Solution 3 | Anirudh Ramanathan |
Solution 4 | acenturyanabit |