Python Set difference() Method
The set.difference()
method returns the new set with the unique elements that are not in the other set passed as a parameter.
Syntax:
set.difference(*other_set)
Parameters:
other_set: (Required) One or more sets separated by a comma.
Return Value:
Returns a new set.
The following example demonstrates the set.difference()
method.
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 8}
nums3 = nums1.difference(nums2)
nums4 = nums2.difference(nums1)
print("nums1 - nums2: ", nums3)
print("nums2 - nums1: ", nums4)
nums1 - nums2: {1, 2, 3}
nums2 - nums1: {8, 6, 7}
The following finds the differences between the two string sets.
cities = {'Bangalore','Mumbai','New York','Honk Kong','Chicago'}
indianCities = {'Bangalore','Mumbai'}
nonindiancities = cities.difference(indianCities)
print("Non-Indian Cities: ", nonindiancities)
Non-Indian Cities: {'Honk Kong', 'Chicago', 'New York'}
Passing Multiple Sets
You can also specify multiple sets in the difference()
method, as shown below.
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 8}
nums3 = { 3, 5, 8, 9, 10}
diff = nums1.difference(nums2, nums3)
print(diff)
{1, 2}
Using the - Operator
The -
operator can also be used for calculating the difference of two sets.
nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 8}
nums3 = { 3, 5, 8, 9, 10}
diff = nums1 - nums2 - nums3
print('Numbers Differences: ', diff)
cities = {'Bangalore','Mumbai','New York','Honk Kong','Chicago'}
indianCities = {'Bangalore','Mumbai'}
nonindiancities = cities - indianCities
print("Non-Indian Cities: ", nonindiancities)
Numbers Differences: {1, 2}
Non-Indian Cities: {'Honk Kong', 'Chicago', 'New York'}