DEV Community

Cover image for What is the difference between ‘is’ and ‘==’ in python
Programmmer
Programmmer

Posted on

What is the difference between ‘is’ and ‘==’ in python

The ‘is’ operator compares the identity (memory location) of two objects while the ‘==’ operator compares the values of two objects.

The ‘==’ operator return True when the values of two operands are equal and false otherwise.

print(True == 1) 
# True means 1 (Python convert the boolean 'True' into integer 1) so True == 1 means 1 == 1

print('1' == 1) 
# '1' means string one and 1 means integer one, in python two different types are not comparable 

print([] == 1) 
# Empty list can't be equal to one

print(10 == 10.0) 
# Python can convert integer and float number, here Python convert them in the same type

print([1,2,3] == [1,2,3]) 
# I hope you understand it

Output

True
False
False
True
True

The ‘is’ operator return True if the variables on either side of the operator point to the same object (same memory location) and false otherwise.

print(True is 1) 
print('1' is 1)
print([] is 1)
print(10 is 10.0)
print([1,2,3] is [1,2,3])
# in all examples both side of 'is' are in the difference location in memory (they are not identical) or you can say they are not same.

Output

False
False
False
False
False

Top comments (3)

Collapse
 
nomade55 profile image
Lucas G. Terracino

What would be a proper True "is" comparation?

Awesome topic btw.

Collapse
 
dwd profile image
Dave Cridland

The typical usages are if you do actually want to know if something is the same instance.

foo = True
if foo is True:  # True!

Also foo is None, which you've probably seen a lot of before, and useful with some constants if you're using them mostly by name, not value, like an enum type in other languages:

class enum:
  LEFT = 'Left'
  RIGHT = 'Right'

foo = enum.LEFT

print(foo is enum.LEFT)  # True! (And doesn't do a string comparison).
Collapse
 
nomade55 profile image
Lucas G. Terracino

Ok now is pretty clear, so at one poin if you change the value of foo to enum.RIGHT, this would be easier than checking if foo == "Right".

Thanks for the heads up!