Python Set symmetric_difference

Now, we are going to learn about the symmetric_difference method. With this method, we get a new set, which is the symmetric difference of these sets(or provided iterables). First of all, Let’s understand what is the symmetric difference. Let’s consider that there are two sets set1 and set2. So, if we are doing a set1.symmetric_difference(set2), then we get a new set, which is a symmetric difference of these sets. This means that the new set will contain the elements which are in the given sets, (set1 or set2), but not in their intersection.

Let’s have a look at an example, which demonstrates the same thing

## Python Set symmetric_difference() Method

As you can see in the above program, we have two simple sets, set1 and set2, and then we are trying to perform set1.symmetric_difference(set2), so, we are going to get a new set, which contains the elements, which are in the given sets, but not in the intersection. The symmetric_difference method returns a new set, which is assigned to the set3 variable. So, in the new set, we can say that the elements ‘W’, ‘J, and ‘Z’ are present. Let’s have a look at the output in our case.

{‘W’, ‘Z’, ‘J’}

As you can see in the output, we got the appropriate elements in the set. So, we can make use of the symmetric_difference method, to get the symmetric difference of the specified sets. We can also provide some other iterable to the method as an argument. Let’s have a look at that too.

As you can see in the above program, we have a set and a list, and then we have passed the list as an argument to the symmetric_difference method. We again get a new set, which contains the elements which are either in the set1, or the list1, but not in their intersection. You can try executing the program and observing the output in this case as well.

So, we can make use of the symmetric_difference method as and when required in the program. Remember that here, we are going to get a new set, which is a symmetric difference between the specified sets. This simply means that the new set will contain elements that are in the given sets, but not in their intersection.