Comparison
is
# is test object id, it is true only if x and y are same objects
l = [1, 2, 3, 4]
l2 = l
l3 = [1, 2, 3, 4]
print(id(l), id(l2)) # same id
if l is l2:
print('l is l2') # print
else:
print('l is not l2')
if l is l3:
print('l is l3')
else:
print('l is not l3') # print
==, compare values
# ==, compare value
l = [1, 2, 3, 4]
l2 = l
l3 = [1, 2, 3, 4]
if l == l2:
print('l is l2') # print
else:
print('l is not l2')
if l == l3:
print('l is l3') # print
else:
print('l is not l3')
#!/usr/bin/python
l = [1, 2, [3, 4]]
l2 = [1, 2, [3, 4]]
print('ID: ', id(l), id(l2)) # l and l2 have different ids
if l == l2:
print('l == l2')# print
else:
print('l != l2')
#!/usr/bin/python
a = 'pub'
b = ''.join(['p', 'u', 'b'])
print(a == b) # True
print(a is b) # False
Compare Objects
class MyAge:
def __init__(self, n):
self.n = n
a1 = MyAge(42)
a2 = MyAge(42)
a1 == a2 # False
class MyAge:
def __init__(self, n):
self.n = n
def __eq__(self, other):
if not isinstance(other, MyAge):
return NotImplemented
return self.n == other.n
a1 = MyAge(42)
a2 = MyAge(42)
a1 == a2 # True
cmp, deprecated in Python 3
Reference