In this short article I describe how to simplify equality comparisons chained with the operator
Do you want to check if a Python 🐍 variable matches one of several possible values?
Instead of writing a big chain of
or and equalities
==, use the
>>> x = 43 >>> if x == 42 or x == 43 or x == 44: ... print("Nice!") ... Nice! >>> if x in (42, 43, 44): ... print("Nice!") ... Nice!
in is a great tip but it isn't always a suitable alternative!
or short-circuits, which means it stops comparing as soon as it finds a
This isn't the case if you use
>>> def f(): ... return 42 ... >>> def g(): ... return 43 ... >>> def h(): ... return 1 / 0 ... >>> if x == f() or x == g() or x == h(): ... print("Nice!") ... Nice! >>> if x in (f(), g(), h()): ... print("Nice!") ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in h ZeroDivisionError: division by zero
You can read more about short-circuiting in this Pydon't article.
For a bonus tip, see @guilatrova's tweet on a similar tip:
I stumbled on an alternative way of comparing many values in Python. 🐍— Gui Latrova (@guilatrova) August 5, 2022
• Define tuples for a shorter comparison.
• Remove the "and" operator
Which way do you prefer? Why? pic.twitter.com/VjZFL8tsQQ
I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza 🍕. Your small contribution helps me produce this content for free and without spamming you with annoying ads.