[Tutor] Off Topic: xrange, WAS: Re: the and command
Kent Johnson
kent37 at tds.net
Fri Aug 24 15:52:16 CEST 2007
Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
>
>> possible = set(xrange(4, 1000, 4)).intersection(xrange(5, 1000, 5))
>> \
>> .intersection(xrange(6, 1000, 6))
>>
>
> Kent,
>
> I've noticed in a few of your replie recemntly you have been using
> xrange rather than range. I was under the impression that since
> iterators were introduced that xrange was more or less just an
> alias for range. Your usage suggests that my understanding is
> wrong?
Yes, you misunderstand. range() still creates a list, xrange() returns a
iterator. In Python 3000 range() will return an iterator and xrange()
will go away.
In [3]: type(range(1000))
Out[3]: <type 'list'>
In [4]: type(xrange(1000))
Out[4]: <type 'xrange'>
> However, even in its original incarnation I would not have used it
> here since I thought its main advantage was in loops where it
> (like a geneator) yielded values one by one to save memory.
> In this case aren't you generating the full set in each case?
> Or at least in the first case, the set()?
I generate the full set but using xrange() avoids creating an
intermediate list. set() is happy to have an iterable argument, it
doesn't need a list. There is an implicit loop; the set constructor must
iterate over its argument. There is a modest performance benefit to
using xrange():
src $ python -m timeit "set(range(1000))"
10000 loops, best of 3: 99.8 usec per loop
src $ python -m timeit "set(xrange(1000))"
10000 loops, best of 3: 86.7 usec per loop
Of course in most cases 13 usec is not of any consequence. In fact in my
own code I usually use range().
Kent
More information about the Tutor
mailing list