<div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">It seems as though Python is actually expanding range(2,n) into a list of<br>
numbers, even though this is incredibly wasteful of memory. There should be<br>
a looping mechanism that generates the index variable values incrementally<br>
as they are needed.</blockquote><div><br></div><div>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.</div>

<div><br></div><div>xrange() returns an iterator, and generates the values on the fly.</div><div><br></div><div>In Python 3, this was changed so range returns an iterator, and to get a list you do list(range(2,n)).</div>
<div>
<br></div><div>--S</div></div>