Join us and get access to thousands of tutorials and a community of expert Pythonistas.

# Union, Intersection, and Difference

Levi

Really liking the breakdown of this.

Sciencificity

Hi James, I think that `symmetric_difference()` only takes one argument since it does not make sense when you apply it to multiple arguments. This is due to the left to right nature of the operator. The in between sets used with `^` can introduce elements that appeared in previous sets but were discarded by the previous use of `^`. E.g using the example we used previously we would have the below:

``````a = {1,2,3,4}
b = {2,3,4,5}
c = {3,4,5,6}
d = {4,5,6,7}
print(a ^ b ^ c ^ d) # a ^ b -> {1,5} ^ c -> {1,3,4,6} ^ d -> {1,3,5,7}

{1, 3, 5, 7} # result ... but 3, 5 occur in multiple sets
``````

Also if we amend the example used in the video slightly (add a 2 in last set):

``````a = {1,2,3,4,5}
b = {10,2,3,4,50}
c = {1,2,50,100}
print(a ^ b ^ c)

{2, 100, 5, 10} # result
``````

Kumaran Ramalingam

Hi James, It was really useful for me to breakdown things and learn

anshetc

The video is incorrect in saying the symmetric_difference operator ‘^’ selects items that are only present in 1 set. An item present in all 3 sets s1, s2, s3 will also show up in s1^s2^s3.

Bartosz Zaczyński RP Team

@anshetc Not exactly. The symmetric difference is a binary operator, which takes two arguments. Python interprets your expression, `s1 ^ s2 ^ s3`, as two separate symmetric differences, i.e., `(s1 ^ s2) ^ s3`.

Consider the following example:

``````>>> s1 = {"a"}
>>> s2 = {"a", "b"}
>>> s3 = {"a", "b", "c"}

>>> s1 ^ s2
{'b'}

>>> {"b"} ^ s3
{'a', 'c'}

>>> s1 ^ s2 ^ s3
{'a', 'c'}
``````

In the above example, `s1 ^ s2` results in `{"b"}` since `"b"` is the symmetric difference between sets `s1` and `s2`. When `{"b"}` is then calculated against `s3` with the symmetric difference, you end up with `{"a", "c"}` because these are the elements that are either in `{"b"}` or `s3` but not in both. Hence, `s1 ^ s2 ^ s3` produces `{"a", "c"}`.

to join the conversation.