A question was posted about chained comparison operators and how they are interpreted in different languages.
Chaining comparison operators means that (x < y < z)
would be interpreted as ((x < y) && (y < z))
instead of as ((x < y) < z)
.
The comments on that question show that Python, Perl 6, and Mathematica support chaining comparison operators, but what other languages support this feature and why is it not more common?
A quick look at the Python documentation shows that this feature has been since at least 1996. Is there a reason more languages have not added this syntax?
A statically typed language would have problems with type conversion, but are there other reasons this is not more common?
Python supports chaining of comparison operators, which means if we wanted to find out if b lies between a and c we can do a < b < c , making code super-intuitive. Python evaluates such expressions like how we do in mathematics.
Chaining with the comparison operator == returns True only if all values are equal. If there is even one different value, False is returned. Be careful when using the comparison operator !=
Equal to ( === ) — returns true if the value on the left is equal to the value on the right, otherwise it returns false .
Summary. A comparison operator compares two values and returns a boolean value, either True or False . Python has six comparison operators: less than ( < ), less than or equal to ( <= ), greater than ( > ), greater than or equal to ( >= ), equal to ( == ), and not equal to ( != ).
It should be more common, but I suspect it is not because it makes parsing languages more complex.
Benefits:
Drawbacks:
As to why not, my guesses are:
The benefit is too small to justify complicating the language.
You don't need it that often, and it is easy to get the same effect cleanly with a few characters more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With