for loop: range() result has too many items

Andre Engels andreengels at gmail.com
Tue Oct 13 23:55:07 CEST 2009


On Tue, Oct 13, 2009 at 11:17 PM, Peng Yu <pengyu.ut at gmail.com> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Quite simple, use xrange (generates the numbers on the fly) rather
than range (creates the list, and gets the numbers from there):

for i in range(sys.maxint):
    if i % 100 == 0:
       print i

However, I think that the better Python way would be to use a generator:

def infinite_numbergenerator():
    n = 0
    while True:
         yield n
         n += 1

for i in infinite_numbergenerator():
    ...


-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list