Combinations of n Lists

Tim Hochberg tim.hochberg at ieee.org
Wed Feb 28 19:09:08 CET 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 ]
>
> print combinations( [1,2,3], ['a','b','c'] )
>
> [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3,
> 'b'), (3, 'c')]
>
> So, what if I want
>
> def combinations(*lists):
>         ....
> print combinations( [1,2,3], [4,5,6], [7,8,9], .... )
>     [ [1,4,7,....],  .... [1,4,8, ... ], ..... ]
>
> Any takers!? ;-)

zip([1,2,3], [4,5,6], [7,8,9], .... )

(New in 2.0 I believe).

or equivalently

map(None, [1,2,3], [4,5,6], [7,8,9], .... )

for you 1.5.2 types out there....

-tim





More information about the Python-list mailing list