Nested loop limit?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • chad

    Nested loop limit?

    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?
    Thanks.
  • Peter Hansen

    #2
    Re: Nested loop limit?

    chad wrote:
    [color=blue]
    > 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?[/color]
    [color=blue][color=green][color=darkred]
    >>> for n in range(100):[/color][/color][/color]
    .... 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[color=blue][color=green][color=darkred]
    >>> print n[/color][/color][/color]
    21

    Yes. :-)

    -Peter

    Comment

    • Ville Vainio

      #3
      Re: Nested loop limit?

      >>>>> "Chad" == chad <chad.himeda@hp .com> writes:

      Chad> I am writing a program to do some reliability calculations
      Chad> that require several nested for-loops. However, I believe
      Chad> that as the models become more complex, the number of
      Chad> required for-loops will increase. Does Python have a limit
      Chad> on the number of nested for-loops? Thanks.

      No idea (probably not), but if you even need to think of such a thing,
      you might want to reconsider the design. 50 or so nested for loops
      wouldn't even fit on the screen due to indentation.

      Typically excessive nesting can be avoided by introduding a function.

      --
      Ville Vainio http://tinyurl.com/2prnb

      Comment

      • Larry Bates

        #4
        Re: Nested loop limit?

        Peter already answered your "specific" question, but
        I thought I'd make a suggestion. If you find yourself
        with LOTS of nested loops, you probably need to take
        a closer look at your class/data structure. Often I
        find that if I find that I'm looping a lot, I probably
        haven't optimized my data storage or object structures
        well. Using list comprehensions can effectively eliminate
        many loops, but your data must be structured in lists of
        numbers (or objects) for them to work well. Functions
        that act on lists of objects can also eliminate many
        nested loops. Lists of objects that themselves hold lists
        of objects can allow you to create complex hierarchies that
        don't require lots of nested lists.

        Just some thoughts that might be of benefit.

        Regards,
        Larry Bates
        Syscon, Inc.


        "chad" <chad.himeda@hp .com> wrote in message
        news:fd07865f.0 407071045.16e20 c84@posting.goo gle.com...[color=blue]
        > 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?
        > Thanks.[/color]


        Comment

        • Nelson Minar

          #5
          Re: Nested loop limit?

          Why does CPython have a limit of 21 nested blocks?

          I'm never going to write code this deeply nested by hand, but I could
          imagine writing a program that does. It's also sort of a weird limit.

          Peter Hansen <peter@engcorp. com> writes:[color=blue][color=green][color=darkred]
          > >>> for n in range(100):[/color][/color]
          > ... 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[color=green][color=darkred]
          > >>> print n[/color][/color]
          > 21
          >
          > Yes. :-)
          >
          > -Peter[/color]

          --

          Comment

          • Peter Hansen

            #6
            Re: Nested loop limit?

            Nelson Minar wrote:
            [color=blue]
            > Why does CPython have a limit of 21 nested blocks?
            >
            > I'm never going to write code this deeply nested by hand, but I could
            > imagine writing a program that does. It's also sort of a weird limit.[/color]

            Is the fact that the limit is actually 20 less weird? (The 21 was
            where "n" was after it raised an exception, not the last legal
            amount of indentation.)

            And I think the answer is probably something like "CPython,
            being written in C, tends to have certain hard-coded limits
            much like C programs always do, rather than being nice and
            flexible like programs written with more sophisticated languages
            like, say, Python." :-)
            [color=blue]
            > Peter Hansen <peter@engcorp. com> writes:
            >[color=green][color=darkred]
            >> >>> for n in range(100):[/color]
            >>... 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[color=darkred]
            >> >>> print n[/color]
            >>21
            >>
            >>Yes. :-)
            >>
            >>-Peter[/color]
            >
            >[/color]

            Comment

            • Michael Hudson

              #7
              Re: Nested loop limit?

              Peter Hansen <peter@engcorp. com> writes:
              [color=blue]
              > Nelson Minar wrote:
              >[color=green]
              > > Why does CPython have a limit of 21 nested blocks?
              > > I'm never going to write code this deeply nested by hand, but I
              > > could
              > > imagine writing a program that does. It's also sort of a weird limit.[/color]
              >
              > Is the fact that the limit is actually 20 less weird? (The 21 was
              > where "n" was after it raised an exception, not the last legal
              > amount of indentation.)
              >
              > And I think the answer is probably something like "CPython,
              > being written in C, tends to have certain hard-coded limits
              > much like C programs always do, rather than being nice and
              > flexible like programs written with more sophisticated languages
              > like, say, Python." :-)[/color]

              Spot on. This has to do with the 'blockstack', very much an internal
              detail to Python's implementation. We'd like to get rid of it (*not*
              because we want to let people write code with more than 20 nested for
              loops :-) but it's not especially easy (finally: blocks are the
              biggest problem).

              Cheers,
              mwh

              --
              I really hope there's a catastrophic bug in some future e-mail
              program where if you try and send an attachment it cancels your
              ISP account, deletes your harddrive, and pisses in your coffee
              -- Adam Rixey

              Comment

              • Dan Bishop

                #8
                Re: Nested loop limit?

                Peter Hansen <peter@engcorp. com> wrote in message news:<FPydnXXVG rDu13HdRVn-uA@powergate.ca >...[color=blue]
                > chad wrote:
                >[color=green]
                > > 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?[/color]
                >[color=green][color=darkred]
                > >>> for n in range(100):[/color][/color]
                > ... 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[color=green][color=darkred]
                > >>> print n[/color][/color]
                > 21[/color]

                However, the code:
                [color=blue][color=green][color=darkred]
                >>> for i in xrange(1000):[/color][/color][/color]
                .... 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.

                Comment

                • Peter Hansen

                  #9
                  Re: Nested loop limit?

                  Dan Bishop wrote:
                  [color=blue]
                  > Peter Hansen <peter@engcorp. com> wrote:[color=green]
                  >>chad wrote:[color=darkred]
                  >>>Does Python have a limit on the number of nested for-loops?[/color]
                  >>
                  >>[Yes. 20][/color]
                  >
                  > However, the code:[/color]
                  [snip][color=blue]
                  > doesn't break until i=227. So if you need more than 20 nested loops,
                  > try replacing them with list comprehensions.[/color]

                  Actually, I think what both our code samples show is that if
                  one needs such a large number of statically nested *anything*,
                  the design is probably broken and should be replaced, if nothing
                  else, with something that builds the code on the fly...

                  If you consider that statically nested for loops must in some
                  way represent different dimensions, is it really possible that
                  a problem can have more than 20 dimensions (or even nearly that
                  many!) which must all be looped over simultaneously? I would
                  try to step way back from my problem and reconsider what I'm
                  doing if I were ever on my way to that situation...

                  But I'd be interested in any ("real world", as usual) example
                  where it is true....

                  -Peter

                  Comment

                  • Dan Christensen

                    #10
                    Re: Nested loop limit?

                    Peter Hansen <peter@engcorp. com> writes:
                    [color=blue]
                    > If you consider that statically nested for loops must in some
                    > way represent different dimensions, is it really possible that
                    > a problem can have more than 20 dimensions (or even nearly that
                    > many!) which must all be looped over simultaneously?[/color]
                    ....[color=blue]
                    > But I'd be interested in any ("real world", as usual) example
                    > where it is true....[/color]

                    Well, in a computation in quantum gravity, I have the C code shown
                    below. It has exactly 20 nested for loops! There are of course
                    other ways to write it, but given the number of iterations, speed
                    is the bottom line. Unfortunately, this is only the simplest test
                    case of a larger problem...

                    I'm converting much of this project to python, but will probably
                    keep this part in C and wrap it with SWIG.

                    Dan

                    (I'm simultaneously embarrassed and proud of this code... :-)

                    #define l1(a) for(Label[a] = 0; Label[a] <= cutoff; Label[a]++)

                    #define l2(a,b,c,d) \
                    for(Label[a] = low3(Label[b],Label[c],Label[d]); \
                    Label[a] <= cutoff && Label[a] <= high3(Label[b],Label[c],Label[d]); \
                    Label[a]+=2)

                    sumF = 0.0;
                    sumFG = 0.0;

                    l1(0)
                    l1(1)
                    l1(4)
                    l2(10,4,0,1)
                    l1(2)
                    l1(5)
                    l2(11,5,0,2)
                    l1(7)
                    l2(13,7,1,2)
                    l2(16,4,5,7)
                    l1(3)
                    l1(6)
                    l2(12,6,0,3)
                    l1(8)
                    l2(14,8,1,3)
                    l2(17,4,6,8)
                    l1(9)
                    l2(15,9,2,3)
                    l2(18,5,6,9)
                    l2(19,7,8,9)
                    {
                    saveF = F();
                    sumF += saveF;
                    sumFG += saveF*obsv();
                    }

                    Comment

                    • Dan Christensen

                      #11
                      Re: Nested loop limit?

                      Peter Hansen <peter@engcorp. com> writes:
                      [color=blue][color=green][color=darkred]
                      > >>> for n in range(100):[/color][/color]
                      > ... exec '\n'.join([(' ' * i) + 'for i%s in range(2):' % i for i in
                      > range(n)])
                      > + '\n' + ' ' * n + 'pass\n'[/color]

                      To tie two threads together, I shudder to think of how unreadable
                      python code could be if there was a ternary operator. :-)

                      Dan

                      Comment

                      • Peter Hansen

                        #12
                        Re: Nested loop limit?

                        Dan Christensen wrote:
                        [color=blue]
                        > Peter Hansen <peter@engcorp. com> writes:[color=green]
                        >>If you consider that statically nested for loops must in some
                        >>way represent different dimensions, is it really possible that
                        >>a problem can have more than 20 dimensions (or even nearly that
                        >>many!) which must all be looped over simultaneously?[/color]
                        >
                        > Well, in a computation in quantum gravity, I have the C code shown
                        > below. It has exactly 20 nested for loops! There are of course
                        > other ways to write it, but given the number of iterations, speed
                        > is the bottom line.[/color]

                        (Thanks for the _real_ real-world example. :-)
                        [color=blue]
                        > #define l1(a) for(Label[a] = 0; Label[a] <= cutoff; Label[a]++)
                        > #define l2(a,b,c,d) \[/color]
                        [snip code sample]

                        I won't claim to have tried, or even to be able, to understand the
                        purpose of the code ;-), but its general appearance suggests to
                        me that it could also be written, perhaps with equivalent or
                        conceivably even better performance, and at least more generality,
                        with some kind of table-driven approach. I'll certainly bow
                        to your better judgment if you've considered that possibility.
                        (And I wonder if you would have written it as statically nested
                        loops if you didn't have macros to fall back on. One might
                        say that you're sort of cheating there, since the loop structure
                        is mostly absent by virtue of having used C.)

                        Anyway, trust an engineer to think the world can be simple,
                        and trust a physicist to show that sometimes it's not. ;-)

                        (Bonvenon al "Pitonujo". Kaj bv. saluti Lindi de mi. :-)

                        -Peter

                        Comment

                        • Ville Vainio

                          #13
                          Re: Nested loop limit?

                          >>>>> "Dan" == Dan Christensen <jdc@uwo.ca> writes:

                          Dan> I'm converting much of this project to python, but will
                          Dan> probably keep this part in C and wrap it with SWIG.

                          While agreeing with Peter about the table driven approach (possibly
                          with some recursion thrown in, the number of recursion levels is not
                          so limited), your code seems like a textbook example of code where C
                          performance is going to murder Python performance, so keeping it in C
                          might indeed make sense if it's run often...

                          --
                          Ville Vainio http://tinyurl.com/2prnb

                          Comment

                          • Dan Christensen

                            #14
                            Re: Nested loop limit?

                            Peter Hansen <peter@engcorp. com> writes:
                            [color=blue]
                            > Dan Christensen wrote:
                            >[color=green]
                            >> Well, in a computation in quantum gravity, I have the C code shown
                            >> below. It has exactly 20 nested for loops! There are of course
                            >> other ways to write it, but given the number of iterations, speed
                            >> is the bottom line.[/color]
                            >
                            > (Thanks for the _real_ real-world example. :-)[/color]
                            ....[color=blue]
                            > its general appearance suggests to
                            > me that it could also be written, perhaps with equivalent or
                            > conceivably even better performance, and at least more generality,
                            > with some kind of table-driven approach. I'll certainly bow
                            > to your better judgment if you've considered that possibility.[/color]

                            Yes, I've considered it, and in fact I'll be forced to use a
                            table-driven approach to handle more general situations, where the
                            geometry is read in from a file. I haven't done timing comparisons,
                            but I would be very surprised if it was faster. There would be some
                            beneficial cache effects from the shorter code, but more lookups and
                            index shuffling which I would expect to slow things down. But maybe
                            I'm not familiar with some tricks that would make this technique
                            faster.

                            As for maintainability of my method, using the macros means that
                            writing the code is very similar to filling in the table in the first
                            place! :-)

                            I've actually toyed with the idea of having the program generate the
                            code (maybe in Python) on the fly, compile it (e.g. with psyco), and
                            then run it. But with Python's limit of 20 nested loops, that won't
                            fly.

                            Dan

                            Comment

                            • Bengt Richter

                              #15
                              Re: Nested loop limit?

                              On Sun, 11 Jul 2004 13:21:37 -0400, Dan Christensen <jdc@uwo.ca> wrote:
                              [color=blue]
                              >Peter Hansen <peter@engcorp. com> writes:
                              >[color=green]
                              >> Dan Christensen wrote:
                              >>[color=darkred]
                              >>> Well, in a computation in quantum gravity, I have the C code shown
                              >>> below. It has exactly 20 nested for loops! There are of course
                              >>> other ways to write it, but given the number of iterations, speed
                              >>> is the bottom line.[/color]
                              >>
                              >> (Thanks for the _real_ real-world example. :-)[/color]
                              >...[color=green]
                              >> its general appearance suggests to
                              >> me that it could also be written, perhaps with equivalent or
                              >> conceivably even better performance, and at least more generality,
                              >> with some kind of table-driven approach. I'll certainly bow
                              >> to your better judgment if you've considered that possibility.[/color]
                              >
                              >Yes, I've considered it, and in fact I'll be forced to use a
                              >table-driven approach to handle more general situations, where the
                              >geometry is read in from a file. I haven't done timing comparisons,
                              >but I would be very surprised if it was faster. There would be some
                              >beneficial cache effects from the shorter code, but more lookups and
                              >index shuffling which I would expect to slow things down. But maybe
                              >I'm not familiar with some tricks that would make this technique
                              >faster.
                              >
                              >As for maintainability of my method, using the macros means that
                              >writing the code is very similar to filling in the table in the first
                              >place! :-)
                              >
                              >I've actually toyed with the idea of having the program generate the
                              >code (maybe in Python) on the fly, compile it (e.g. with psyco), and
                              >then run it. But with Python's limit of 20 nested loops, that won't
                              >fly.
                              >
                              >Dan[/color]
                              How many total executions of the innermost loop are you expecting?

                              At 2 states per nested loop, ISTM you'd have 2**20 unless some logic prunes it (not bad).
                              But at say 10 states per nested loop, ISTM 10**20 would imply a long wait (>3000 years
                              if you could do a billion loops/second ;-), unless you have a way of parallelizing
                              over a LARGE farm and CONSIDERABLE pruning happens.

                              Perhaps a clue to your real problem might yield some ideas for alternatives
                              to massive nested looping, where just the repeated control overhead of the innermost
                              loops by itself could add up to a long wait.

                              Regards,
                              Bengt Richter

                              Comment

                              Working...