1

If I have 3 lists - 'a', 'b', and 'c', and I want to find every possible combination which consists of one value from each loop, that's easy.

a = [1,2,3]
b = [4,5,6]
c = [7,8,9]

def combo_finder(a,b,c):
    result = []
    for x in a:
        for y in b:
            for z in c:
                result.append([x,y,z])
    return result

Or to write it so it can take a single argument, like this:

l = [a,b,c]
def combo_finder(l):
    result = []
    for x in l[0]:
        for y in l[1]:
            for z in l[2]:
                result.append([x,y,z])
    return result

But say i need it to accomodate an argument l that contains n number of lists inside? How can I create nested for loops on demand? I've tried writing recursively, but I seem to keep running into infinite recusion that way.

Bennie
  • 509
  • 1
  • 4
  • 19

1 Answers1

3

I'm not sure why Reut deleted a valid answer - so I'm re-posting my version to it (using itertools.product):

import itertools
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
l = [a,b,c]
print [x for x in itertools.product(*l)]

OUTPUT

[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9)]
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • 1
    Yes, that is exactly what I need. I didn't know product could take multiple lists like that. Not very clear in the docs. Reut's answer was close, but this one showed how to pass an iterable as a single argument using the * , which was needed in this case. Thanks alfasin! – Bennie May 16 '15 at 02:34