tags:

views:

81

answers:

2

how can I get the list of cross product pairs from a list of arbitrarily long lists in python? e.g.

a = [1,2,3]
b = [4,5,6]

crossproduct(a,b) should yield [[1,4], [1, 5], [1,6], ...]

thanks.

+5  A: 

You're looking for itertools.product if you're on (at least) Python 2.6.

>>> import itertools
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> itertools.product(a,b)
<itertools.product object at 0x10049b870>
>>> list(itertools.product(a,b))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
ChristopheD
Note that for pre-2.6 use, you can simply copy-and-paste the pure Python implementation from the linked documentation.
Mike Graham
+5  A: 
[(x, y) for x in a for y in b]
Cory Petosky