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.

Example: difference()
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)
Output
nums1 - nums2: {1, 2, 3}
nums2 - nums1: {8, 6, 7}

The following finds the differences between the two string sets.

Example: difference()
cities = {'Bangalore','Mumbai','New York','Honk Kong','Chicago'}
indianCities = {'Bangalore','Mumbai'}
nonindiancities = cities.difference(indianCities)
print("Non-Indian Cities: ", nonindiancities)
Output
Non-Indian Cities:  {'Honk Kong', 'Chicago', 'New York'}

Passing Multiple Sets

You can also specify multiple sets in the difference() method, as shown below.

Example: Multiple Parameters
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)
Output
{1, 2}

Using the - Operator

The - operator can also be used for calculating the difference of two sets.

Example: - Operator
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)
Output
Numbers Differences: {1, 2}
Non-Indian Cities: {'Honk Kong', 'Chicago', 'New York'}
Want to check how much you know Python?