Python Set union
Now, we are going to learn about the union method. If you are already familiar with the union operation on the set, you can simply get this method easily. But even if you are not familiar with the operation, do not worry, since we would study this operation from the basics, so you can simply follow along.
Let’s say that we have 2 sets, set1, and set2. If we do set1.union(set2), we get a new set, which is the union of the two sets. This simply means that the new set will contain the elements that are in either set. Do not worry if you are still confused about what this method is returning. Once we have the output, we would try to visualize what is happening. Let’s have a look at the program first.
Python Set union() Method
As you can see in the above program, we have two sets, set1, and set2, and both have some elements. Then we are trying to do set1.union(set2). The union method returns a set, which is the union of two sets. This simply means that the resultant set contains the elements, which are in either set. The output of the above program comes out to be something like this –
{1, 2, 3, 5, 7, 9, 11, 13}
As you can see, we have the output set, in which, all the elements that are present in either set, are included. So, whenever we need to perform the union of the sets (or we can also give other iterable as arguments to the method), we can make use of the union method.
Alternatively, we can make use of the | operator as well, to perform the union operation. Let’s have a look at that as well.
As you can see in the above program, we can make use of the | operator to perform the union operation over the sets. You can try executing the program and observing the output as well. So, this is the union method. When we need to perform the union operation on the sets, we can make use of the union method, or the | operator to do so.