How to Perform the Union Operation on Sets in Python using the Sympy Module
In this article, we show how to perform the union operation on sets in Python using the sympy module.
The union of 2 sets is a set that contains all of the distinct members of the two sets.
The union of multiple sets (2 or more), again, is a set that contains all of the distinct members of all of the sets.
In mathematics, in set theory, the symbol ∪ refers to union 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 {1,2,3,4,5,6}.
In sympy, there is a union() function which allows us to
perform the union operation on sets.
How to Create a Union Between 2 Sets
So we'll now show how to create a union 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 a union between sets using the union() 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 union() function to perform the union operation on the 2 sets.
This gives us the set, (1,2,3,4)
And this is a union operation between 2 sets in Python.
How to Create a Union Between Multiple Sets
So now what we have more than 2 sets.
How can we create a union between multiple sets (greater than 2)?
The answer, you can use the union function multiple times as needed for each additional set that you want to do the union operation on after performing a union on 2 sets.
This is shown in the code below.
So you can see how we use the union() operation again to perform the union operation on an additional set (after performing union on the first 2).
We perform the union operation on all 3 sets and this gives us
a new set of (1,2,3,4,5,6).
And this is how we can perform the mathematical union operation on
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