Combining arbitrary lists

Thorsten Kampe thorsten at thorstenkampe.de
Mon Nov 15 08:15:35 EST 2004


* Nick (2004-11-15 04:28 +0100)
> Given that
> 
> n = [ [1, 2, 3], [4, 5, 6], [7, 8] ]
> 
> then the following code produces what I expect
> 
> for x in n[0]:
>    for y in n[1]:
>      for z in n[2]:
>        print [x, y, z]
> 
> --output--
> [1, 4, 7]
> [1, 4, 8]
> [1, 5, 7]
> [1, 5, 8]
>   ...
> [3, 6, 8]
> --      --
> 
> How can I do this for an arbirary length of n?

This is the Cartesian product of three sets. Have a look at
http://www.thorstenkampe.de/python/utils.py:

def cartes(seq0, seq1, modus = 'pair'):
    """ return the Cartesian Product of two sequences """
    if   modus == 'pair':
        return [[item0, item1] for item0 in seq0 for item1 in seq1]
    elif modus == 'triple':
        return [item0 + [item1] for item0 in seq0 for item1 in seq1]

Then you would generate your output like this:
>>> cartes(cartes([1, 2, 3], [4, 5, 6]), [7, 8], 'triple')



More information about the Python-list mailing list