Python Symmetric Difference With Examples

In this tutorial, you will learn the Python Symmetric Difference Method with Examples that help you to implement this tutorial.

What is Symmetric Difference in Python?

The symmetric_difference() method returns a set that has all the items from both sets but not the items that are in both sets. The returned set has a mix of things that aren’t in either of the two sets.

Syntax

set.symmetric_difference(set)

Parameter Values

ParameterDescription
setRequired. The set to check for matches in
Python Symmetric Difference – Parameter Values

Return Value

The symmetric_difference() method returns:

a set with all the items of A and B excluding the excluding the identical items

How Do You Find The Symmetric Difference of Two Lists In Python?

Example 1: Python Set symmetric_difference()

The symmetric difference() method of the Set type gives you the symmetric difference between two or more sets.

new_set = set1.symmetric_difference(set2, set3,...)

For example, to find the symmetric difference between the s1 and s2 sets, do the following:

s1 = {'Python', 'Java', 'C++'}
s2 = {'C#', 'Java', 'C++'}

s = s1.symmetric_difference(s2)

print(s)

Program Output:

{'C#', 'Python'}

Note: that the symmetric difference() method returns a new set and doesn’t change the original sets.

Example 2: Python Symmetric Difference Using ^ Operator

To find the symmetric difference between two or more sets, you can use the set symmetric_difference() method or the symmetric difference operator (^).

new_set = set1 ^ set2 ^...

The example below shows how to use the symmetric difference operator (^) on the sets s1 and s2:

s1 = {'Python', 'Java', 'C++'}
s2 = {'C#', 'Java', 'C++'}

s = s1 ^ s2

print(s)

Program Output:

{'Python', 'C#'}

The symmetric_difference() method vs symmetric difference operator (^)

The symmetric_difference() method can take one or more iterables, which can be strings, lists, or dictionaries.

If the iterables aren’t sets, the method will turn them into sets before returning the symmetric difference of them.

The following example shows how to find the symmetric difference between a set and a list using the symmetric_difference() method:

scores = {7, 8, 9}
ratings = [8, 9, 10]
new_set = scores.symmetric_difference(ratings)

print(new_set)

Program Output:

{10, 7}

The symmetric difference operator (^), on the other hand, only works with sets. You’ll get an error if you try to use it with iterables that aren’t sets.

Summary

  • The symmetric difference of two or more sets is a group of elements that are in all sets but not in their intersections.
  • To find the symmetric difference between two or more sets, use the set symmetric_difference() method or the symmetric difference operator (^).

Inquiries

However, if you have any questions or suggestions about this tutorial Python Symmetric Difference, Please feel free to comment below, Thank You!

Leave a Comment