My Google-fu has failed me.
In Python, are the following two tests for equality equivalent?
n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!'
Does this hold true for objects where you would be comparing instances (a list
say)?
Okay, so this kind of answers my question:
L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't.
So ==
tests value where is
tests to see if they are the same object?
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory.
The == operator checks to see if two operands are equal by value. The === operator checks to see if two operands are equal by datatype and value.
The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.
is
will return True
if two variables point to the same object (in memory), ==
if the objects referred to by the variables are equal.
>>> a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True # Make a new copy of list `a` via the slice operator, # and assign it to variable `b` >>> b = a[:] >>> b is a False >>> b == a True
In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:
>>> 1000 is 10**3 False >>> 1000 == 10**3 True
The same holds true for string literals:
>>> "a" is "a" True >>> "aa" is "a" * 2 True >>> x = "a" >>> "aa" is x * 2 False >>> "aa" is intern(x*2) True
Please see this question as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With