Check if a given value is out of certain range

Steven D'Aprano steve at
Wed Sep 30 03:55:57 CEST 2015

On Wed, 30 Sep 2015 07:07 am, Ian Kelly wrote:

> On Tue, Sep 29, 2015 at 3:04 PM, Random832 <random832 at> wrote:
>> How about x not in range(11)?
> That's fine as long as x is known to only take integral values.

It's not fine. In Python 2, it's painfully slow and inefficient, both
memory-wise and algorithmically:

-1 in range(100000000)  # test 0 <= -1 <= 100000000

This first creates a list of 100000000 integers, then compares each and
every one of them against -1 before returning False.

Using xrange instead at least avoids building the list first, but it still
compares -1 against each value.

Testing a numeric value within a certain range of values should be constant
time and constant memory. It should be *fast*. Using range in Python 2 is
none of those things.


More information about the Python-list mailing list