Skip to main content

Chained Comparison

·132 words·1 min
Posts 101 python
Table of Contents
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).

Related

Insecurity in HTTP Headers
·2195 words·11 mins
Posts Essential async cli http python
Based on essential security, here is how to protect users by securing HTTP headers for a website.
HTTP Versioning
·740 words·4 mins
Posts async cli http python tools
HTTP/1 vs HTTP/1.1 vs HTTP/2 vs HTTP/3
Python Rich Package
·121 words·1 min
Posts cli python
Enrich python cmdline apps with RICH.