Search code examples
pythonpython-3.xcomparison-operators

Checking if a tuple is in range


In my level editing program, I have the following code, which removes game pieces that have moved out of the playable area:

x, y = theobj.pos
if x not in range(0,79):
    level.remove_obj(theobj)
if y not in range(0,29):
    level.remove_obj(theobj)

Is there any efficient way I can simplify this to a single if statement? I've considered using list comprehension to generate a list of all valid position tuples, but that seems a little bit bloated.


Solution

  • You could use:

    if not (0 <= x <= 78 and 0 <= y <= 28):
        level.remove_obj(theobj)
    

    This uses chained comparisons to test against two boundaries for both x and y.

    I'd not create range() objects here; you are creating a new object for each test.

    Demo:

    >>> x, y = 10, 10
    >>> (0 <= x <= 78 and 0 <= y <= 28)
    True
    >>> x, y = 10, 42
    >>> (0 <= x <= 78 and 0 <= y <= 28)
    False
    >>> x, y = 81, 10
    >>> (0 <= x <= 78 and 0 <= y <= 28)
    False