Creating unique combinations from lists

Tim Chase python.list at tim.thechases.com
Wed Jan 16 17:22:56 EST 2008


>> I could do nested for ... in loops, but was looking for a Pythonic way
>> to do this.  Ideas?
> 
> What makes you think nested loops aren't Pythonic?

On their own, nested loops aren't a bad thing.  I suspect they 
become un-Pythonic when they make code look ugly and show a 
broken model of the problem.  There's a big diffence between:

   # iterate over a 10x10 grid
   for i in xrange(10):
     for j in xrange(10):
       print i,j

which is pretty manageable, but quickly becomes very unpythonic 
if the problem is poorly defined:

  for a in range(5):
   for b in range(5):
    for c in range(5):
     for d in range(5):
      for e in range(5):
       for f in range(5):
        for g in range(5):
         for h in range(5):
          for i in range(5):
           for j in range(5):
            for k in range(5):
             for l in range(5):
              for m in range(5):
               for n in range(5):
                for o in range(5):
                 for p in range(5):
                  for q in range(5):
                   for r in range(5):
                    for s in range(5):
                     for t in range(5):
                      for u in range(5):
                       for v in range(5):
                        for w in range(5):
                         for x in range(5):
                          for y in range(5):
                           for z in range(5):
                            print a,b,c,d,e,f,g,
                            print h,i,j,k,l,m,n,
                            print o,p,q,r,s,t,u,
                            print v,w,x,y,z

It gets even worse if your loop nesting is based on something 
external.  You wouldn't want code that looks like

   if len(input) == 2:
     for a in range(5):
       for b in range(5):
         whatever(a,b)
   elif len(input) == 3:
     for a in range(5):
       for b in range(5):
         for c in range(5):
           whatever(a,b,c)
   elif len(input) == 4:
   ...

Contributing to the unpythonic'ness (unpythonicity?) of it is 
that something is clearly happening at a higher level than just 
for-loops so other Python constructs should be used to express 
them instead of abusing your code to do your dirty work.

-tkc









More information about the Python-list mailing list