287
votes

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?

2
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

2 Answers

473
votes

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

12
votes

It can be rewritten as:

start <= x <= end:

Or:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....