Python Set difference() Method
Python Set difference() Method
The set.difference() method in Python returns the set difference of two sets(A-B).
Syntax
set.difference(set1)
Parameter
set- This argument represents a set (minuend)
set1- This arguments represents a set(subtrahend)
Return
This method returns the difference of the two specified sets i.e. the returned set will contain the items that exist only in the first set, and not in both sets.
Example 1
# Python program explaining
# the set.difference() method
#initializing a set with numbers from 1 to 10
Numbers = {1,2,3,4,5,6,7,8,9,10}
print("Numbers:",Numbers)
# initializing set2 with even numbers
even = {2,4,6,8}
print("Even numbers: ",even)
# Equivalent to A-B
# Numbers- even= Odd
print("After subtracting even numbers from Natural numbers... ")
print("Odd numbers: ",Numbers.difference(even))
Output
Numbers: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Even numbers: {8, 2, 4, 6}
After subtracting even numbers from Natural numbers...
Odd numbers: {1, 3, 5, 7, 9, 10}
Example 2
# Python program explaining
# the set.difference() method
#initializing a set with alphabets A to Z
Alphabets = {'a', 'b', 'c', 'd','e',
'f','g','h','i',
'j','k','l','m',
'n','o','p','u',
'v','w','x','y','z'}
print("Alphabets:",Alphabets)
# initializing set2 with vowels
vowels = {'a', 'e', 'i','o','u'}
print("vowels: ",vowels)
# Equivalent to A-B
# Alphabets- vowels= Consonants
print("After subracting vowels from Alphabets... ")
print("Consonants: ",Alphabets.difference(vowels))
Output
Alphabets: {'o', 'v', 'h', 'p', 'n', 'w', 'b', 'l', 'g', 'z', 'x', 'c', 'e', 'j', 'k', 'f', 'i', 'a', 'm', 'y', 'd', 'u'}
vowels: {'a', 'u', 'o', 'i', 'e'}
After subracting vowels from Alphabets...
Consonants: {'k', 'y', 'v', 'f', 'g', 'z', 'd', 'x', 'h', 'p', 'n', 'w', 'b', 'c', 'l', 'm', 'j'}
