My new ebook βComprehending Comprehensionsβ is on pre-sale and 40% off!

## Simplifying equality comparisons with or

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