Search notes:
Python: comparison operators
Apparently, comparison operators are also called
relational operators . These include:
Chaining comparison operators
Comparison operators can be chained:
def F(a, b, c):
if a < b < c:
print('{} < {} < {}'.format(a, b, c))
if a < b > c:
print('{} < {} > {}'.format(a, b, c))
F(10, 20, 30)
#
# 10 < 20 < 30
F(11, 22, 15)
#
# 11 < 22 > 15
F(10, 20, 5)
#
# 10 < 20 > 5
Comparing sequences
Sequences can be compared. When sequences are compared, the interpreter compares the sequences' elements pairwise from left to right until it is clear what the comparison evaluates to.
If a compared element is a seqeunce itself, the comparison is done recursively.
print ( [ 42, 'Hello world' ] < [ 42, 'ZZZZ' ] ) # True
print ( [ 42, 'Hello world' ] < [ 42, 'Hello world', 1 ] ) # True
print ( [ 42, 'Hello world', 1 ] < [ 42, 'Hello world' ] ) # False
print ( [ 7, (3,2,1) , 8 ] < [ 7, (9, 8, 7) , 1 ] ) # True
It is not possible to compare a
list with a
tuple . This raises a
TypeError
exception ('<' not supported between instances of 'tuple' and 'list')
Comparision of user defined types
Without implementing __eq__
, ==
is always false in user defined types:
#!/usr/bin/python3
class C:
def __init__(self, a, b):
self.a = a
self.b = b
c1 = C(5, 3)
c2 = C(5, 3)
c3 = C(1, 9)
if c1 == c2:
print('c1 == c2')
else:
print('c1 != c2')
# c1 != c2
if c1 == c3:
print('c1 == c3')
else:
print('c1 != c3')
# c1 != c3
In order to have a meaningful equality test of user defined types, the __eq__
method needs to be implemented
#!/usr/bin/python3
class C:
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return self.a == other.a and self.b == other.b
c1 = C(5, 3)
c2 = C(5, 3)
c3 = C(1, 9)
c4 = C(5, 9)
if c1 == c2:
print('c1 == c2')
else:
print('c1 != c2')
# c1 == c2
if c1 == c3:
print('c1 == c3')
else:
print('c1 != c3')
# c1 != c3
if c1 == c4:
print('c1 == c4')
else:
print('c1 != c4')
# c1 != c4