In this short article I describe how to simplify equality comparisons chained with the operator or
.
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 in
operator!
>>> x = 43
>>> if x == 42 or x == 43 or x == 44:
... print("Nice!")
...
Nice!
>>> if x in (42, 43, 44):
... print("Nice!")
...
Nice!
Using in
is a great tip but it isn't always a suitable alternative!
The operator or
short-circuits, which means it stops comparing as soon as it finds a True
.
This isn't the case if you use in
:
>>> 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
This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book βPydon'tsβ teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here ππ.