Simplify Chained Comparison
102,152
Solution 1
In Python you can "chain" comparison operations which just means they are "and"ed together. In your case, it'd be like this:
if start <= x <= end:
Reference: https://docs.python.org/3/reference/expressions.html#comparisons
Solution 2
It can be rewritten as:
start <= x <= end:
Or:
r = range(start, end + 1) # (!) if integers
if x in r:
....
Related videos on Youtube
Author by
Brynn McCullagh
Updated on October 19, 2020Comments
-
Brynn McCullagh over 3 years
I have an integer value
x
, and I need to check if it is between astart
andend
values, so I write the following statements:if x >= start and x <= end: # do stuff
This statement gets underlined, and the tooltip tells me that I must
simplify chained comparison
As far as I can tell, that comparison is about as simple as they come. What have I missed here?
-
Edward Ned Harvey almost 5 yearsIf you get a suggestion from the tooltip, you can mouseover the area and it gives you a little light-bulb. You can click on it and have it automatically insert the change it's suggesting. So you can see what it thinks you should be doing (and you can Undo if you don't like it).
-
-
Burhan Khalid over 9 yearsThe range is a poor choice because for large start and end you are creating an unnecessary list.
-
Maroun over 9 years@BurhanKhalid Indeed,but I guess it's worth mentioning for OP.
-
Brynn McCullagh over 9 yearsThanks, I didn't know you could do that in Python. Was really scratching my head on this one.
-
JoshNahum about 9 yearsIn python3, range handles "contains" nicely, so no list is generated.
-
dvdvck almost 8 years@MarounMaroun since python 3, range function behaves like former xrange, it is also worth mentioning
-
Kevin J. Chase about 7 yearsFor details regarding the use of
if x in range(...)
, see "Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?". -
Hakaishin over 6 yearsMan this is how things should be. But coming from other languages you forget your ideals and don't even think, that things could be the way they should be. But this is why python is amazing, exactly because of such things :)
-
Ray almost 6 yearsDo you know of any "official" sources that recommends the chained style over the other? Which one is more "idiomatic" Python?
-
BallpointBen over 5 yearsI dunno, sometimes I wish python threw up more guardrails. x == y == z fails with a ValueError when x, y, z are Pandas series
-
John Zwinck over 5 years@BallpointBen: lots of things don't work the way you might expect in Pandas, not even
x == y and y == z
. -
pfabri about 4 years@Ray The linked reference above explicitly states that Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.