Combinations of n Lists

Alex Martelli aleaxit at yahoo.com
Wed Feb 28 11:14:32 EST 2001


"Warren Postma" <embed at geocities.com> wrote in message
news:NI8n6.2979$TW.15640 at tor-nn1.netcom.ca...
> I was just wondering if anyone has a more general version of this little
> helper function:
>
> def combinations(list1,list2):
>     return [ (i,j) for i in list1 for j in list2 ]
    [snip]
> def combinations(*lists):
>         ....
> print combinations( [1,2,3], [4,5,6], [7,8,9], .... )
>     [ [1,4,7,....],  .... [1,4,8, ... ], ..... ]

As usual, the easiest approach is through recursion, e.g.:

def combinations(*lists):
    if not lists: return [ [] ]
    more = combinations(*lists[1:])
    return [ [i]+js for i in lists[0] for js in more ]


Alex






More information about the Python-list mailing list