range() is not the best way to check range?
John Machin
sjmachin at lexicon.net
Tue Jul 18 07:55:20 EDT 2006
On 18/07/2006 7:22 PM, Paul Boddie wrote:
> John Machin wrote:
>> On 18/07/2006 12:41 PM, Summercoolness at gmail.com wrote:
>>> it seems that range() can be really slow:
>
> [...]
>
>> Some things to try:
>> 1a. Read what the manual has to say about the range() function ... what
>> does it produce?
>
> Indeed. Still, the addition of a __contains__ method to range (and
> xrange) would permit acceptable performance for the code given. Perhaps
> this is a convenience worth considering for future Python releases.
>
range() and xrange() are functions. You are suggesting that 2
*functions* should acquire a __contains__ method each? I trust not.
Perhaps you meant that the acquisitors should be the objects that those
functions return.
range() returns a list. Lists already have a __contains__ method. It's
been getting a fair old exercising in the last few hours, but here we go
again:
>python -mtimeit -s"x=range(30000)" "x.__contains__(40000)"
1000 loops, best of 3: 1.09 msec per loop
>python -mtimeit -s"x=range(30000)" "40000 in x"
1000 loops, best of 3: 1.09 msec per loop
>python -mtimeit -s"x=range(30000)" "x.__contains__(1)"
1000000 loops, best of 3: 0.434 usec per loop
>python -mtimeit -s"x=range(30000)" "1 in x"
1000000 loops, best of 3: 0.137 usec per loop
A __contains__ method for xrange objects? The case of x in xrange(lo,
hi) is met by lo <= x < hi. IMHO, anyone who wants x in xrange(lo, hi,
step) should be encouraged to do the necessary algebra themselves; I
wouldn't suggest that any core dev time be wasted on implementing such
folderol.
In any case, isn't the *whole* xrange gizmoid on GvR's I-wish-I-hadn't list?
Cheers,
John
More information about the Python-list
mailing list