problems caused by very large for-loop

true911 true911m at gmail.com
Thu Dec 7 22:23:22 EST 2006


sam wrote:
> hi all,
> ...

> has anyone else bumped up against this problem before? i suppose
> for-loops with 250 million iterations are seldom used in most
> applications. it was just the first time i'd ever solved a problem by
> actually having some insight into how python works at a slightly lower
> level.

Sam,

The problem is not with the 'for' operator, but the fact that the
range() operator creates the iterable list (in this case, with 250
million elements) prior to beginning the loop.

Try using xrange() with the same syntax, which returns items from a
tuple (NOT a list, if it matters to you) just-in-time and discards
them, much like FOR as used in a BASIC context.

xrange() is somewhat less flexible, though, and may or may not suit
your needs.  If not, use 'while' instead, and set your own loop exit
conditions.




More information about the Python-list mailing list