My new ebook β€œComprehending Comprehensions” is on pre-sale and 40% off!

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:

This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.

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.

Previous Post Next Post

Blog Comments powered by Disqus.