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

Alan Morgan amorgan at xenon.Stanford.EDU
Wed Apr 5 19:24:18 EDT 2006


In article <e11i3l$hvt$1 at news.albasani.net>,
Georg Brandl  <g.brandl-nospam at gmx.net> wrote:
>Alan Morgan wrote:
>> In article <teXYf.69673$A83.1673324 at twister1.libero.it>,
>> Giovanni Bajo <noway at sorry.com> wrote:
>>>Steve R. Hastings wrote:
>>>
>>>>> in Python 2.X, range is defined to return a list.  if you start
>>>>> returning something else, you'll break stuff.
>>>>
>>>> Perhaps I'm mistaken here, but I don't see how this optimization could
>>>> possibly break anything.
>>>
>>>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?
>> Obviously there *are* differences, viz:
>
>Just _look_ at the objects:
>
>>>> range(5)
>[0, 1, 2, 3, 4]
>>>> xrange(5)
>xrange(5)
>>>>

Yes, I was well aware of this.  I noted a difference in my original
post.  I was just pointing out that the example given didn't, in
fact, behave differently for range() and xrange() even though range()
and xrange() *are* different.

>range is giving you a real list, while xrange is giving you an xrange object.
>Have you tried to slice an xrange object? Or using .append on it?

No, I hadn't.  I presume these could all be defined.

Alan
-- 
Defendit numerus



More information about the Python-list mailing list