Nested loop limit?

Dan Bishop danb_83 at yahoo.com
Fri Jul 9 15:19:43 EDT 2004


Peter Hansen <peter at engcorp.com> wrote in message news:<FPydnXXVGrDu13HdRVn-uA at powergate.ca>...
> chad wrote:
> 
> > I am writing a program to do some reliability calculations that
> > require several nested for-loops.  However, I believe that as the
> > models become more complex, the number of required for-loops will
> > increase.  Does Python have a limit on the number of nested for-loops?
>  
>  >>> for n in range(100):
> ...   exec '\n'.join([(' ' * i) + 'for i%s in range(2):' % i for i in 
> range(n)])
>   + '\n' + ' ' * n + 'pass\n'
> ...
> Traceback (most recent call last):
>    File "<stdin>", line 2, in ?
> SystemError: too many statically nested blocks
>  >>> print n
> 21

However, the code:

>>> for i in xrange(1000):
...    try:
...       exec '[0 %s]' % ' '.join(['for k%d in [0]' % j for j in
xrange(i)])
...    except:
...       print i
...       break

doesn't break until i=227.  So if you need more than 20 nested loops,
try replacing them with list comprehensions.



More information about the Python-list mailing list