r/ProgrammerTIL • u/cdrini • Sep 12 '17
Python [Python] TIL that you can chain comparisons
For example:
x = 3
0 < x < 10 # -> TrueWikipedia: https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators
Python Docs: https://docs.python.org/3/reference/expressions.html#comparisons
Edit: formatting
69
Upvotes
View all comments
Show parent comment
4
u/cdrini Sep 12 '17 edited Sep 13 '17
I think the reason Python has comparison chaining is because it goes very well with "The Zen of Python".
if 0 < x < 10:is much more beautiful and simple thanif 0 < x and x < 10:. I would say writing the latter knowing the former exists is bad code style. (Apparently PyCharm suggests this as well, but only for monotonic chains; PEP8 doesn't mention it).This feature is pretty rare. I learned about the fact that Python supports this while reading the Julia documentation (Julia also supports comparison chaining). I did some searching and it looks like Perl 6, Mathematica, and Lisp (actually only supports monotonic chaining:
(<= 0 x 10)) support comparison chaining. (stackoverflow:language-support-for-chained-comparison)My guess as to why it isn't very common would be because of the 'standard' set by C and because it makes parsing more complex. In C,
0 < x < 10is evaluated as(0 < x) < 10=>1 < 10=>1. JavaScript and even C++ behave in the same way, while C# and Java throw errors. My guess would be parsing becomes a little annoying since0 < xcan be a bool or... something else depending on whether it's followed by another relational operator, but I'm not too sure how that works. (enwiki:Relational_operator#Operator_chaining)In short, yes, the generalization can lead to messy code if used incorrectly, but if we can trust children to use the
<and>operators sanely in math, then I think we can trust programmers to do so, too :)E: a word; correction