how to get elements of two sets that are only in one in python

To get the elements that are only in one set and not in the other set, you can use the set symmetric difference operator ^ in Python.

Here's an example:

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

only_in_set1 = set1 ^ set2
only_in_set2 = set2 ^ set1

print("Elements only in set1:", only_in_set1)
print("Elements only in set2:", only_in_set2)
200 chars
9 lines

Output:

main.py
Elements only in set1: {1, 2, 3}
Elements only in set2: {8, 9, 7}
66 chars
3 lines

In this example, set1 ^ set2 gives the elements that are only in set1, and set2 ^ set1 gives the elements that are only in set2.

related categories

gistlibby LogSnag