efficiency of range() and xrange() in for loops

Erik Max Francis max at alcyone.com
Wed Apr 5 18:50:23 EDT 2006


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


-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   I will always remember / This moment
   -- Sade



More information about the Python-list mailing list