'How do I get the symmetric intersection between Python sets?
I've been learning about Python sets recently. Let's say we have two sets:
set1 = {'dog', 'cat', 'hamster'}
set2 = {'monkey', 'dog'}
I know how to get the symmetric difference:
>>> set1.symmetric_difference(set2)
{'hamster', 'cat', 'monkey'}
But how do I get the symmetric intersection?
>>> set1.symmetric_intersection(set2)
...
AttributeError: 'set' object has no attribute 'symmetric_intersection'
Solution 1:[1]
There is no such thing as a "symmetric intersection" for set operations, in Python or generally in mathematics/set theory.
The available set operations between two sets that result in a new set are union, intersection, difference and symmetric_difference.
| Operation | Equivalent | Result |
|---|---|---|
| s.union(t) | s | t | new set with elements from both s and t |
| s.intersection(t) | s & t | new set with elements common to s and t |
| s.difference(t) | s - t | new set with elements in s but not in t |
| s.symmetric_difference(t) | s ^ t | new set with elements in either s or t but not both |
Between these operations, all the possible relationships between 2 sets are covered.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
