how to get the cartesian product of two sets in python

You can use the product function from the itertools module to get the cartesian product of two sets. Here's an example:

main.py
import itertools

set1 = {1, 2, 3}
set2 = {'a', 'b'}

cartesian_product = itertools.product(set1, set2)

print(list(cartesian_product))
136 chars
9 lines

Output:

main.py
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
61 chars
2 lines

In this example, set1 contains the numbers 1, 2, and 3, and set2 contains the letters 'a' and 'b'. We use the product function to get the cartesian product of the two sets, which returns an iterator of tuples. We convert this iterator to a list and print the result.

Note that the order of the sets passed to product does not affect the result. The cartesian product of {1, 2, 3} and {'a', 'b'} is the same as the cartesian product of {'a', 'b'} and {1, 2, 3}.

gistlibby LogSnag