Python itertools product() - How to make Cartesian products by two lists

You can make Cartesian products using itertools.product() in Python.

import itertools

p = itertools.product([1, 2, 3], ['A', 'B'])

print(p)  # <itertools.product object at 0x1140f6400>

for i in p:
    print(i)

# (1, 'A')
# (1, 'B')
# (2, 'A')
# (2, 'B')
# (3, 'A')
# (3, 'B')

Cartesian products can be made by Python list comprehension.

a = [1, 2, 3]
b = ['A', 'B']

c = [(m, n) for m in a for n in b]

for i in c:
    print(i)

# (1, 'A')
# (1, 'B')
# (2, 'A')
# (2, 'B')
# (3, 'A')
# (3, 'B')

Python Itertools

Python Tutorial