how to get the difference of two sets in python

In Python, we can get the difference of two sets by using the '-' operator or by calling the difference() method on one of the sets.

Here's an example using the difference() method:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

diff = set1.difference(set2)

print(diff)  # Output: {1, 2, 3}
110 chars
7 lines

And here's an example using the '-' operator:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

diff = set1 - set2

print(diff)  # Output: {1, 2, 3}
100 chars
7 lines

Both of these approaches will result in a new set that contains the elements that are in set1 but not in set2. If you want to get the symmetric difference (i.e. the elements that are in one set but not the other), you can use the symmetric_difference() method:

main.py
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

sym_diff = set1.symmetric_difference(set2)

print(sym_diff)  # Output: {1, 2, 3, 6, 7, 8}
137 chars
7 lines

In this case, the resulting set contains all elements that are in set1 or set2 but not in both.

gistlibby LogSnag