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

Steve R. Hastings steve at hastings.org
Wed Apr 5 18:46:12 EDT 2006


On Wed, 05 Apr 2006 22:09:29 +0000, Giovanni Bajo wrote:
> [...] you assume that the only use-case of range() is within a for-loop.

No, I do not assume any such thing.  I have not suggested that range()
should be changed to always return an iterator.  I wondered if the Python
compiler could, as a special case, turn:

for i in range(n)

into compiled code equivalent to

for i in itr

where "itr" is a lightweight iterator that returns the same values as
iter(range(n)).

iter(range(n)) will still allocate a list of n integers, and then produce
an iterator over that list, so I did not mean to suggest that for would
simply call iter() when you use "for i in range".

I apologize if my writing was unclear.
-- 
Steve R. Hastings    "Vita est"
steve at hastings.org    http://www.blarg.net/~steveha




More information about the Python-list mailing list