Home / Posts / Chaining comparison operators View Raw
25/08 — 2020
15.98 cm   1.4 min

Chaining comparison operators

I recently came across this lesser known feature in Python and started to play around with it.

Being able to chain comparison operators is a rarity among most modern programming languages, which is a shame considering how elegant and intuitive it turns out to be.

Here are some examples:

a, b, c = 5, 10, 15
print(a < b < c)
# True

The code above is equivalent to:

a, b, c = 5, 10, 15
print(a < b and b < c) 
# True

And something a bit more complex:

a, b, c, d, e, f, g = 5, 10, 30, 20, 15, 0, 0
flag = a <= b > f < c > d is not f is g
print(flag)
# True

That is all equivalent to:

a, b, c, d, e, f, g = 5, 10, 30, 20, 15, 0, 0
flag = a <= b and b > f and f < c and c > d and d is not f and f is g
print(flag)
# True

You can see how tedious things might get. Python continues to amaze me with how beautiful and concise it can be.

Hi.

I'm Liam.

I'm currently a software engineer intern at 1Password on the Filling and Saving team, where I primarily work on the browser extension and related infrastructure.

I also study computer science at McGill University.

I like developer tooling, distributed systems, performance engineering and compiler design.

You can reach out to me via email at liam@scalzulli.com.

Home / Posts / Chaining comparison operators View Raw