Python 'for' loop is memory inefficient

Stephen Hansen apt.shansen at gmail.com
Fri Aug 14 21:30:43 EDT 2009


>
> It seems as though Python is actually expanding range(2,n) into a list of
> numbers, even though this is incredibly wasteful of memory. There should be
> a looping mechanism that generates the index variable values incrementally
> as they are needed.


This has nothing to do with Python's for loop (and saying the loop construct
itself is memory inefficient makes me blink in confusion): but you've
isolated the problem precisely all on your own. range() is defined as
returning a list. Thus, it constructs the list all at once.

xrange() returns an iterator, and generates the values on the fly.

In Python 3, this was changed so range returns an iterator, and to get a
list you do list(range(2,n)).

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090814/c3e8f738/attachment-0001.html>


More information about the Python-list mailing list