Checking if a number is not in range in Python

Issue

I have Python code at the moment which does something like this:

if plug in range(1, 5):
    print "The number spider has disappeared down the plughole"

But I actually want to check if the number is not in range. I’ve googled and had a look at the Python documentation, but I can’t find anything. How can I do it?

Additional data: When running this code:

if not plug in range(1, 5):
    print "The number spider has disappeared down the plughole"

I get the following error:

Traceback (most recent call last):
    File "python", line 33, in <module>
IndexError: list assignment index out of range

I also tried:

if plug not in range(1,5):
     print "The number spider has disappeared down the plughole"

Which returned the same error.

Solution

If your range has a step of one, it’s performance-wise much faster to use:

if not 1 <= plug < 5:

Than it would be to use the not method suggested by others:

if plug not in range(1, 5)

Proof:

>>> import timeit
>>> timeit.timeit('1 <= plug < 5', setup='plug=3')  # plug in range
0.053391717400628654
>>> timeit.timeit('1 <= plug < 5', setup='plug=12')  # plug not in range
0.05137874743129345
>>> timeit.timeit('plug not in r', setup='plug=3; r=range(1, 5)')  # plug in range
0.11037584743321105
>>> timeit.timeit('plug not in r', setup='plug=12; r=range(1, 5)')  # plug not in range
0.05579263413291358

And this is not even taking into account the time spent on creating the range.

Answered By – Markus Meskanen

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.