Just leant that Python does support chained comparison.
In Python, using chained comparison operators is a way to simplify multiple comparison and thus more efficient.
Comparisons#
# comparison operators
comparisons = [
'<', '>', '<=', '>=', '==', '!=',
'is', 'is not', 'in', 'not in'
]
Chained_Comparison#
I didn’t know that Python does support chained comparison until today.
I used to do this in the past:
def main():
x, y, z = 0, 1, 2
if x < y and y < z:
print(True)
else:
print(False)
By using chained comparison, I can simply do this way:
def main():
x, y, z = 0, 1, 2
if x < y < z:
print(True)
else:
print(False)
The difference between the two methods above is, the y
is evaluated only once (in method 2).