Pairwise crossproduct in Python

PythonList

Python Problem Overview


How can I get the list of cross product pairs from a list of arbitrarily long lists in Python?

Example

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

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

Python Solutions


Solution 1 - Python

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)]

Solution 2 - Python

Since you asked for a list:

[(x, y) for x in a for y in b]

But you can avoid the overhead of a list if you're just looping through these by using generators instead:

((x, y) for x in a for y in b)

Behaves identically in a for loop but doesn't result in the creation of a list.

Solution 3 - Python

Using generators there is no need for itertools, simply:

gen = ((x, y) for x in a for y in b)

for u, v in gen:
    print u, v

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser248237View Question on Stackoverflow
Solution 1 - PythonChristopheDView Answer on Stackoverflow
Solution 2 - PythonCory PetoskyView Answer on Stackoverflow
Solution 3 - PythonRabih KodeihView Answer on Stackoverflow