Skip to content

Python set difference method | Example code

  • by

Use the difference() method to get the difference between sets in Python. The Python difference() method returns a set that contains the difference between two sets.

If 
A = {1, 2, 3, 4}

AND 
B = {2, 3, 9}

Then,
A - B = {1, 4}
B - A = {9}

Simply it returns set containing items that exist only in the first set, and not in both sets.

set1.difference(set2)

Python set difference example

Simple example code.

set1 = {'A', 'B', 'C', 'D'}
set2 = {'C', 'F', 'G'}

print(set1.difference(set2))

print(set2.difference(set1))

Output:

Python set difference method

Set Difference Using – Operator

You can also use the – operator to get the difference between sets.

set1 = {'A', 'B', 'C', 'D'}
set2 = {'C', 'F', 'G'}

print(set1 - set2)

print(set2 - set1)

Output:

{‘B’, ‘A’, ‘D’}
{‘F’, ‘G’}

What is the set difference() method vs set difference operator (-)

Answer: The set difference() method can accept one or more iterables (e.g., strings, lists, dictionaries) while the set difference operator (-) only allows sets.

When passing iterables to the set difference() method, it’ll convert the iterables to sets before performing the difference operation.

Do comment if you have any doubts or suggestions on this Python set code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading