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

Steve R. Hastings steve at hastings.org
Wed Apr 5 19:42:28 EDT 2006


On Thu, 06 Apr 2006 09:08:45 +1000, Steven D'Aprano wrote:
> Yes, the above example is a good use case for xrange. Did you think that
> anyone denied that there were good cases for it?

I am now officially sorry for starting this thread.



Please let me just summarize what I wanted to say:

* Question: Does Python do anything special with "for i in range"?
(And I got an answer: the answer is "no".)

* If Python does not do anything special with "for i in range", then you
are building a list and tearing it down again without using the list, and
for memory efficiency you might want to use xrange.  (I used a more pithy
phrase, which I now regret.)

* It would be nice if the Python compiler checked for the special case of
"for i in range" and compiled it to "for i in itr" where itr is a
lightweight iterator that generates the same values as the range statement.
Potentially, I speculated, this special iterator might be more lightweight
than an xrange() object.


That is all.  I did not mean to tell anyone how to write a for loop.  I
did not mean to suggest that range() should be changed to always return an
iterator.  I did not mean to insult anyone.  I don't even know what I ever
wrote that sounded like "range should never be used".

And I hope everyone recognized that the bit about "those responsible...
have been sacked" was a reference to the opening credits of the movie
_Monty Python and the Holy Grail_.  I was trying to be funny, not
sarcastic, bitter, etc.

Thank you for your patience and I am done with this thread, unless I have
written something unclear in *this* post and I have to post another post
to clarify it as well. :-(
-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list