range() is not the best way to check range?

Diez B. Roggisch deets at nospam.web.de
Tue Jul 18 13:22:33 EDT 2006


Simon Forman wrote:

> Nick Craig-Wood wrote:
>>
>> Sets are pretty fast too, and have the advantage of flexibility in
>> that you can put any numbers in you like
>>
> 
> I know this is self-evident to most of the people reading this, but I
> thought it worth pointing out that this is a great way to test
> membership in range(lo, hi, step) without doing "the necessary
> algebra".
> 
> i.e.  n in set(xrange(0, 10000, 23)) ...

No, its not. It works, but it works by no means faster than 

n in range(0, 10000, 23)

Both need O(n), which is a bit slow compared to

(((n - 15) % 23) == 0 and n >= 15 and n < 10000)

that will run in O(1)

Diez



More information about the Python-list mailing list