efficiency of range() and xrange() in for loops
Alan Morgan
amorgan at xenon.Stanford.EDU
Wed Apr 5 20:02:16 EDT 2006
In article <F4KdnXuGqOst1KnZnZ2dnUVZ_vudnZ2d at speakeasy.net>,
Erik Max Francis <max at alcyone.com> wrote:
>Alan Morgan wrote:
>
>> In article <teXYf.69673$A83.1673324 at twister1.libero.it>,
>> Giovanni Bajo <noway at sorry.com> wrote:
> >
>>>Because you assume that the only use-case of range() is within a for-loop.
>>>range() is a builtin function that can be used in any Python expression. For
>>>instance:
>>>
>>>RED, GREEN, BLUE, WHITE, BLACK = range(5)
>>
>> Hmmm, this worked fine when I used xrange as well. Am I missing something?
>
>Not in your use case. Tuple unpacking will iterate, and so it doesn't
>matter whether it's an actual list or an iterator:
>
> >>> a, b, c = xrange(3)
> >>> a
>0
> >>> b
>1
> >>> c
>2
>
>There are certainly contexts where a sequence and its iterator are not
>interchangeable. You missed an obvious one:
>
> >>> range(3) == xrange(3)
>False
I thought that one was sufficiently obvious as not to need mentioning.
There was never any argument that range() and xrange() returned different
things; the question (as I understood it) was if you could generally
use the things they return in the same way and not *care* about the
difference (the answer being "Yes, except when you can't").
Alan
--
Defendit numerus
More information about the Python-list
mailing list