Simplify Chained Comparison

PythonPycharm

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 - Python

It can be rewritten as:

start <= x <= end:

Or:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrynn McCullaghView Question on Stackoverflow
Solution 1 - PythonJohn ZwinckView Answer on Stackoverflow
Solution 2 - PythonMarounView Answer on Stackoverflow