# How to Obtain the Cartesian Product of Two Sets in Python using the Sympy Module

In this article, we show how to obtain the cartesian product of two sets in Python using the sympy module.

The cartesian product is the set that consists of all possible pairs of each of the elements of one set with all of the elements of the other set. You can think of it as all of the possible combinations of sets that can be made from each of the elements in each of the two sets.

For example, if we have two sets, where set 1 is {1,2} and set 2 is {3,4}, this will create a cartesian product that consists of 4 sets: ((1,3),(1,4),(2,3),(2,4)).

So below we write code that obtains the cartesian product of two sets in Python using the sympy module.

So let's now go over this code.

So we must import the sympy module and the FiniteSet from the sympy module.

We create a variable, set1, which we initialize to a FiniteSet composed of the members 1 and 2.

We then create another variable, set2, which we initialize to a FiniteSet composed of the members 3 and 4.

To get the cartesian product of these two sets, we simply use the * operator. This gets the cartesian product of two sets. The cartesian product, again, is a combination of all of each of the members of one set with all of the members of the other set.

We assign this cartesian product to the variable, cartesianproduct.

We show this variable, cartesianproduct, and you can now see that it is a ProductSet of the two sets, set1 and set2.

In order to get the individual sets that compose this cartesian product set, we use a for loop.
With this for loop, you can then see all of the sets that compose this cartesian product.

And this is how we can obtain the cartesian product of two sets in Python using the sympy module.

Related Resources

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python