Python Program To Find Cartesian (Cross) Product Of 2 List

This Python program calculates Cartesian product of two sets. Cartesian product is also known as Cross product.

Cartesian product example: if setA = [1, 2, 3] and setB = [a, b] then output setA X setB = [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

Cartesian product of two sets can be obtained easily using list comprehension. See Python source code below:

Python Source Code: Cross Product


setA = [1, 2, 3]
setB = ['a', 'b']

cross_product = [(i,j) for i in setA for j in setB]

print(cross_product)

Output

[(1, 'a'), (1, 'b'), (2, 'a'), 
(2, 'b'), (3, 'a'), (3, 'b')]