Get Difference in Sets in Python
In Python, a set refers to an unordered collection of unique elements. Sets plays a very fundamental role in storing extensive and verstaile data type both in mathematics and programming.
One of the most common task when working with sets is determining the difference between two set values. In this tutorial, we will learn the various methods we can use to determine set differences in Python.
Sets Basics
In Python, we can create a set by enclosing a comma-separated sequence of elements within curly braces {}
:
s = {1, 2, 3}
We can also create a set by using the set()
constructor.
s2 = set([4, 5, 6])
Set Elements
In Python, a set cannot contain duplicate values which means that each value is unique in the specified set. Adding a duplicate value in the set is automatically rejected.
Example:
s = {1, 2, 2, 3}
print(s)
In this case, the element 2
is removed from the set.
Set Difference
Let us explore the various methods of determining the set differences in Python. We will use the following set values for demonstration:
s = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6, 7}
Method 1 - Using the -
Operator
The most basic method is by using the subtraction operator. We can find the difference between two sets using the -
as it returns elements that are in the first set but not in the second set.
An example is as shown:
s = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6, 7}
diff = s - s2
print(diff)
Output:
{1, 2}
The above output shows the missing elements in the second set but are available in the first set.
Method 2 - Using difference()
Method
Did you know there is a method called difference()
?. This method allows us to determien the difference between two set values.
The method will only return the difference between the two set values without modifying the original sets.
An example is as shown:
s = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6, 7}
diff = s.difference(s2)
print(diff)
Output:
{1, 2}
Method 3 - Using difference_update()
Method
Unlike the difference()
method, the difference_update()
method will modify the original set and set its values as the missing sets.
An example is as shown:
s = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6, 7}
diff = s.difference_update(s2)
print(s)
Output:
{1, 2}
In this case, the method updates the values of the first set to contain the missing elements.
Method 4 - Using Symmetric Difference
Symmetric difference returns elements that are in either of the sets, but not in their intersection. An example is as shown:
s = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6, 7}
diff = s.symmetric_difference(s2)
print(s)
Output:
{1, 2, 3, 4, 5}
Conclusion
In this post, we learned how to work with sets and explored the various methods and techniques of determining the difference between set values.