Tip 14 Chain Comparison Operators
Pythonic Programming — by Dmitry Zinoviev (23 / 116)
👈 Chapter 2 General Tips | TOC | Expand the Tabs 👉
★2.7, 3.4+ Remember how you could write in an algebra class that x < y < z? In Python, you can chain comparison operators, too: x < y < z. You can even write x < y <= z != w, why not? An expression like this is evaluated first by evaluating each comparison operator separately and then taking the and of the results:
x < y and y <= z and z != w
You could even evaluate bizarre expressions like x < y > z (check if y is greater than both x and z) — but they are confusing and better avoided.
👈 Chapter 2 General Tips | TOC | Expand the Tabs 👉
Pythonic Programming by Dmitry Zinoviev can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.