nested for loop

Terry Reedy tjreedy at udel.edu
Mon May 10 21:03:39 EDT 2004


"Wolfgang Buechel" <wjb131 at web.de> wrote in message
news:4629559b.0405101330.286ddb32 at posting.google.com...
> Hi,
>
> I want to iterate over all 2x2 matrices with elements in range 0..25
> (crypto-stuff).
>
> To produce them, first I wrote a fourfold nested for loop:
>
> M=26
>    for a in range(M):
>       for b in range (M):
>          for c in range (M):
>             for d in range (M):
>                  matr = [[a,b],[c,d]]
> (dosomething)

This is completely clear and space efficient.

> Then I had a look in comp.lang.python and found:

Oh dear...

> for (a,b,c,d) in [(x,y,z,t)  for x in range(M)
>                              for y in range(M)
>                              for z in range(M)
>                              for t in range(M)] :
>    matr = [[a,b],[c,d]]

This is less clear.  It took me about 10 seconds (versus 1) to see as
equivalent.  It produces a list with M**4 elements that you don't actually
need and soon throw away.

> Is there a shorter (and probably, with respect to exec time, faster)
> way to write such a 4for loop?

Write a C extension, maybe with Pyrex.  However, an hour of your time is
worth lots of hours of PC time.  But for a million runs, it might be worth
it.

Terry J. Reedy







More information about the Python-list mailing list