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

Simon Forman rogue_pedro at yahoo.com
Wed Jul 19 00:50:02 EDT 2006


tac-tics wrote:
> Simon Forman wrote:
> > To me, and perhaps others, "T =
> > set(xrange(0, 10000, 23))" and "n in T"  are somewhat easier to read
> > and write than "not n % 23 and 0 <= n < 10000", YMMV.
>
> Eh? How is the first easier to read than the second?? You have a nested
> function call in the first!

I find the first form more immediately comprehensible than the latter.
I know what xrange() does, and I know what set() does, and "nested
function calls" give me no trouble,  whereas the latter form with a
modulus, negation, and comparisons would take me a bit longer both to
compose and/or understand.

If this is not the case for you then by all means please disregard my
posting.  YMMV.

>
> Regardless, testing if a member is part of a ranged set is always going
> to be slower.

Yes.  Roughly 0.0000001 seconds slower on my five year old computer.
I'm not worried.

> It's the nature of what you're doing. Building a set and
> then searching it takes much longer than a single modulus and
> subtraction (which is all an integer comparison is).

Building the set, yes, but searching the set is very close to the same
speed, even for rather large sets.  If you were performing the search
30000 times (like in the OP) it would only take about three thousandths
of a second longer, and that's on my old slow computer.

If I were doing this a thousand times more often, or on a range of a
million or more, or in production code, or with ranges that changed
often, then I would certainly take the time to write out the latter
form.


Peace,
~Simon




More information about the Python-list mailing list