nested for loop

Peter Hansen peter at engcorp.com
Mon May 10 19:51:00 EDT 2004


Wolfgang Buechel wrote:

> 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)
> 
> Then I had a look in comp.lang.python and found:
> 
> 
> 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]]
> 
> Is there a shorter (and probably, with respect to exec time, faster) 
> way to write such a 4for loop?

Hmm... why would you want something shorter, as it would
probably be less readable?  Also, how fast do you need it
to run, or how many times faster than the above would you
like it to run?

(The second one is a facetious question... the first is
more serious.  In effect: what's wrong with what you have?)

-Peter



More information about the Python-list mailing list