List Combinations

Mel mwilson at the-wire.com
Wed Mar 12 11:31:47 EDT 2008


Gerdus van Zyl wrote:
> I have a list that looks like this:
> [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]
> 
> how can I get all the combinations thereof that looks like as follows:
> 3,9,5,4,2
> 3,1,5,4,2
> 3,9,5,4,5
> 3,1,5,4,5
> etc.
> 
> Thank You,
> Gerdus

What they said, or, if you want to see it done:


def combi (s):
     if s:
         for a in s[0]:
             for b in combi (s[1:]):
                 yield [a] + b
     else:
         yield []

for y in combi ([['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]):
     print y



More information about the Python-list mailing list