Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between "==" and "is"?

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?

like image 572
Bernard Avatar asked Sep 25 '08 12:09

Bernard


People also ask

What is difference between IS and == in Python?

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.

What is == and === in Python?

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.

Is there any difference between == and === in a comparison?

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.


1 Answers

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.

like image 189
Torsten Marek Avatar answered Sep 22 '22 15:09

Torsten Marek