for loop: range() result has too many items

Mel mwilson at the-wire.com
Tue Oct 13 17:29:10 EDT 2009


Peng Yu wrote:

> Hi,
> 
> The following code does not run because range() does not accept a big
> number. Is there a way to make the code work. I'm wondering if there
> is a way to write a for-loop in python similar to that of C style.
> 
> for(int i = 0; i < a_big_number; ++ i)
> 
> Regards,
> Peng
> 
> $ cat for_loop.py
> import sys
> 
> def foo():
>   for i in range(sys.maxint):
>     if i % 100 == 0:
>       print i
> 
> foo()
> $ python for_loop.py
> Traceback (most recent call last):
>   File "for_loop.py", line 8, in <module>
>     foo()
>   File "for_loop.py", line 4, in foo
>     for i in range(sys.maxint):
> OverflowError: range() result has too many items

Are you using Python 2.x ???  If you are, range will accept your number, but 
it will try to build a list holding sys.maxint integers, and you don't have 
enough memory.

Try xrange instead.

	Mel.





More information about the Python-list mailing list