﻿ How to Perform the Intersection Operation on Sets in Python using the Sympy Module ﻿

# How to Perform the Intersection Operation on Sets in Python using the Sympy Module

In this article, we show how to perform the intersection operation on sets in Python using the sympy module.

The intersection of 2 sets is a set that contains all of the members that are in common between 2 sets.

The intersection of multiple sets (2 or more), again, is a set that contains all of the members that are common in all of the sets.

In mathematics, in set theory, the symbol ∩ refers to intersection between sets. Therefore, if set A is {1,2,3,4} and set B is {3,4,5,6}, set A ∩ set B would create a new set composed of {3,4}.

In sympy, there is an intersect() function which allows us to perform the intersection operation on sets.

### How to Create an Intersection Between 2 Sets

So we'll now show how to create an intersection between 2 sets.

This is shown in the code below.

So let's now go over this code.

So the first we have to do is import the sympy module and FiniteSet.

The sympy module allows us to create an intersection between sets using the intersect() function.

The FiniteSet from the sympy module allows us to create a mathematical set (as opposed to a standard Python set).

After this, we create a variable, set1, which contains the elements (1,2,3)

Then we create a second variable, set2, which contains the elements (2,3,4)

We then use the intersect() function to perform the intersection operation on the 2 sets.

This gives us the set, (2,3)

And this is an intersection operation between 2 sets in Python.

### How to Create an Intersection Between Multiple Sets

So now we deal with intersection of more than 2 sets.

How can we create an intersection between multiple sets (greater than 2)?

The answer, you can use the intersect function multiple times as needed for each additional set that you want to do the intersection operation on after performing an intersection on 2 sets.

This is shown in the code below.

So you can see how we use the intersect() operation again to perform the intersection operation on an additional set (after performing the intersection operation on the first 2).

We perform the intersection operation on all 3 sets and this gives us a new set of (3, 4).

And this is how we can perform the mathematical intersection operation on sets in Python using the sympy module.

Related Resources