Make a cartesian product from two tuples in Python

Here is an example to make a cartesian product of two tuples in Python.

x = ('a', 'b')
y = ('c', 'd')

z = tuple((i, j) for i in x for j in y)

# (('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'))

# <class 'tuple'>

The i and j are the local variables iterating x and y respectively. The pair of i and j is an element of the cartesian product. The expression in the round brackets is called a generator expression and in fact it's a generator as follows.

x = ('a', 'b')
y = ('c', 'd')

g = ((i, j) for i in x for j in y)

print(g)  # <generator object <genexpr> at 0x110b2feb0>
print(type(g))  # <class 'generator'>

z = tuple(g)

print(z)  # (('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'))

Python generator is often used to combine multiple tuples or lists like this.

x = (1, 2)
y = (3, 4)

g = (i * j for i in x for j in y)

z = tuple(g)

print(z)  # (3, 4, 6, 8)

Each element of the new tuple is the multiplication of x's number and y's number.


Powered by Markdown