4

I have a problem I'm trying to solve which requires nesting as many levels deep as there are items in a list. Or to be precise, iterables in a list.

def example(arg_list):
for i in arg_list[0]:
    for j in arg_list[1]:
        for k in arg_list[2]:
            print "{} {} {}".format(i,j,k)

The above function would run fine as long as the "arg_list" is a list containing 3 iterables, such as [[1,3,4],[4,5,6], [9,3,2,1,0]]. If there were always four iterables in the list, that would be easy to do as well. I need to figure out how to create a function that will add another nested level for each iterable added to the "arg_list" parameter. It seems that recursion might be the way to go, but haven't been able to figure that out.

Bennie
  • 509
  • 1
  • 4
  • 19

2 Answers2

7

What you are looking for is called a Cartesian product. Python's itertools module has a function that will do that for you.

from itertools import product

def example(arg_list):
    for items in product(*arg_list):
        print " ".join(str(item) for item in items)
kindall
  • 178,883
  • 35
  • 278
  • 309
  • this works, i should have checked itertools. Small edit, since product was imported by itself, it should read "for items in product(*arg_list):... no need to say "...in itertools.product..." – Bennie Dec 22 '15 at 18:35
0

You could use recursion, something like:

def example(arg_list, res=[]):
    if arg_list == []:
        print res
        return
    for i in arg_list[0]:
        example(arg_list[1:], res+[i])
Julien
  • 13,986
  • 5
  • 29
  • 53