r/learnpython • u/[deleted] • Jun 12 '21
What is the difference between "is" and ==?
5 is 5 returns True, just as 5 == 5 returns True. What is the difference?
56
u/Euphoric-Quality-424 Jun 12 '21
5 == 5.0 returns True , because they are mathematically equal.
5 is 5.0 returns False , because one is an int and the other is a float, so they cannot both be stored at the same memory location.
3
1
u/TciddaecnacT Jun 12 '21
Would it be fair to say:
'is' evaluates for exactness
'==' evaluates for sameness
1
u/Euphoric-Quality-424 Jun 13 '21 edited Jun 13 '21
"exactness" is a bit vague. In purely mathematical terms, 5 and 5.0 are "exactly" equal - they are just different representations of the same number. (Any disagreement about this would be more philosophical than mathematical.)
Also, "sameness" can be subjective: it depends on how the == operator is defined for the objects in question. One good example of this is NaN ("not a number") as defined in modules like
math,numpy, etc.Code:
from math import nan print(nan is nan) print(nan == nan)Output:
True FalseExplanation:
There is only one
nanobject, sonan is nanreturnsTrue.But when you have two variables that both have the value
nan, that doesn't mean they are "equal" (they are just equally meaningless in numerical terms). Sonan == nanreturnsFalse.0
Jun 12 '21
[deleted]
1
u/Brian Jun 12 '21
251 is 251 is False
Actually, that'll still be True. One reason is that the cache goes up to 256, so this is still in the cached range, but even if you did
260 is 260, it'd still say True, because python will compile that line as one compilation step, and notice that the same values are used in multiple places and reuse the object. You'd need to do something like split it over multiple lines:>>> a = 260 >>> a is 260 False
16
Jun 12 '21
This GitHub post explains what is happening: https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator
10
4
u/lele3000 Jun 12 '21
Besides what others answered, one practical way of looking at it is that you can overload == but not is.
For example:
class MyClass:
def __init__(self, value):
self.value = value
def __eq__(self, value):
return self.value == value
a = MyClass(2)
a == 2 % returns True
a is 2 % returns False and displays warning
a = MyClass(None)
a == None % returns True
a is None % returns FalseThis is for example often used in numpy where == is overloaded to perform vector wise comparison and also returns a vector, while is performs object wise comparison:
import numpy as np
a = np.array([None, None, None])
a == None % returns array([ True, True, True])
a is None % returns False4
u/____candied_yams____ Jun 12 '21
I think this is right:
a == bchecks equality:a.__eq__(b)a is bchecks identity:id(a) == is(b)
3
u/py_vel26 Jun 12 '21 edited Jun 12 '21
I'm glad I came across this post. I'm new to Python but it makes sense to me. A dollar bill is not 4 quarters but they have equal value. $1 is $1(4 quarters) FALSE or $1 == $1(4 quarters) TRUE
2
u/mayankkaizen Jun 12 '21
Every thing is object in Python and every object has a value, a type and an ID. The is operator checks if both objects have same ID (and therefore same value and type). If this returns True, it means both objects are one and same.
OTOH, == operator merely checks for value. It doesn't say anything about ID.
a = [1,2]
b = [1,2]
c = "foo"
d = "foo"
a == b #True
a is b #False, see below
c is d #True
c == d #TrueNote that since list is of mutable type, above a and b are guaranteed to refer two different objects even though they have the same values. Hence == returns true but is returns false.
For strings and numbers in range [-5,256], operation
`c` is `d` #if both have same valuewill always return True. The same is not true for mutable types.
1
u/Moraedka Jun 12 '21
If you had tried coding in JavaScript, there is a '===' comparison operator. What's the difference of === and ==?
The answer is simple:
==compares both of the objects' values. Returns atrueboolean value if both have the same value, regardless of data type.===compares both of the objects values and data types. Returns a true boolean value if both have the same value and data types.
Since JavaScript is a dynamically-typed language, he has to implement type comparison. Same goes for Python, except replacing === with is.
If we have some float x and int y with similar values (assumed to be 69, nice), then:
x is y
>>> False
x == y
>>> True1
u/backtickbot Jun 12 '21
1
u/DrMaxwellEdison Django and stuff Jun 12 '21
5 is 5 is equivalent to id(5) == id(5). Have a look at the id() built-in function for details.
Essentially, is tests that two objects are the same object in memory. id() returns that memory identifier.
The reason 5 is 5 still returns True is because small integers and strings are treated as singletons in memory for convenience. Python does not bother to create two different objects to represent those small values: it just finds the first one cached in memory and returns that one.
If you tried 12345678 is 12345678, you would likely get a False (on mobile, cannot double check).
0
Jun 12 '21
[deleted]
9
Jun 12 '21
Just completely and utterly wrong. Is compares whether they refer to the same object. == compares the values.
24
Jun 12 '21
[removed] — view removed comment
1
u/gaurav_lm Jun 12 '21
Yes this. While there are great explanation here, I'd recommend OP to learn about id( ) method.
674
u/shiftybyte Jun 12 '21 edited Jun 12 '21
You have two identical blue cars in front of you.
They are the same model make and color.
The cars are equal, but the left car is not actually the right car...
Same with objects in memory, equals means they have the same value, "is" means it actually points to the same object.