Using chained comparison operators in Python

In Python, there are the usual comparison operators: <, <=, >, >=, ==, !=.

But one thing Python allows you to do that is not so common is chaining comparison operators more succinctly.

Consider the example below using a well-known syntax with the ‘and’ keyword:

x = 30
y = 50
z = 60

if( x < y and y < z):
    print('y is right in the middle')

The example above works just fine, but we can further simplify it to:

x = 30
y = 50
z = 60

if( x < y < z):
    print('y is right in the middle')

In this case, ‘y’ is evaluated only once, which can give you some small speed advantage when working with large chunks of data.