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

K.S.Sreeram sreeram at tachyontech.net
Tue Jul 18 13:34:04 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)) ...

This is very very misleading... here are some timings :

python -mtimeit "n=5000" "n in set(xrange(0,10000))"
1000 loops, best of 3: 1.32 msec per loop

python -mtimeit "n=5000" "n in xrange(0,10000)"
1000 loops, best of 3: 455 usec per loop

python -mtimeit "n=5000" "0 <= n < 10000"
1000000 loops, best of 3: 0.217 usec per loop

sets are fast only if you create them *once* and use them again and
again. even in that case, the sets use up O(n) memory.

with comparison operators, you don't need extra memory *and* there is no
pre-computation required.

[sreeram;]

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 260 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20060718/2d15ab91/attachment.sig>


More information about the Python-list mailing list