318

I have an integer value x, and I need to check if it is between a start and end 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?

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
Brynn McCullagh
  • 4,083
  • 2
  • 17
  • 12
  • 3
    If 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). – Edward Ned Harvey Aug 08 '19 at 11:50

2 Answers2

517

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

Trey Hunner
  • 10,975
  • 4
  • 55
  • 114
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 5
    Thanks, I didn't know you could do that in Python. Was really scratching my head on this one. – Brynn McCullagh Oct 22 '14 at 09:29
  • 30
    Man 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 :) – Hakaishin Jan 30 '18 at 14:10
  • 1
    Do you know of any "official" sources that recommends the chained style over the other? Which one is more "idiomatic" Python? – Ray Sep 13 '18 at 16:33
  • 1
    I dunno, sometimes I wish python threw up more guardrails. x == y == z fails with a ValueError when x, y, z are Pandas series – BallpointBen Jan 12 '19 at 00:50
  • 1
    @BallpointBen: lots of things don't work the way you might expect in Pandas, not even `x == y and y == z`. – John Zwinck Jan 14 '19 at 12:23
  • @Ray The linked [reference above](https://docs.python.org/3/reference/expressions.html#comparisons) 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._ – pfabri May 27 '20 at 12:31
13

It can be rewritten as:

start <= x <= end:

Or:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
Maroun
  • 94,125
  • 30
  • 188
  • 241