Python: Dictionaries and Sets

Theory: Methods of set objects

Making operations on sets as methods

You've already learned about operators that allow you to combine sets. These operators are as similar as possible to those used in set theory in mathematics. Every programmer should at least know the basics of set theory. For this reason, we should use sets in combination with operators.

However, we should mention that each operator has a verbal equivalent method:

a.union(b)                 # equivalent "a | b"
a.intersection(b)          # equivalent "a & b"
a.difference(b)            # equivalent "a - b"
a.symmetric_difference(b)  # equivalent "a ^ b"

Updating of sets in place

There is another reason why we're talking about the four methods above. Remember, we looked at the dictionary update method, updating the dictionary locally using data from another dictionary? There are several of these sorts of update methods.

The difference_update method

The difference_update works similarly to - or difference. It removes from the set all elements that are in the set argument of the associated one:

a, b = {1, 2}, {2, 3}
a.difference_update(b)
a  # {1}

The intersection_update method

The intersection_update is the modifying analog of & or intersection. It leaves only those elements in the linked set that are in the argument set:

a, b = {1, 2}, {2, 3}
a.intersection_update(b)
a  # {2}

The symmetric_difference_update method

The symmetric_difference_update is the modifying analog of ^ or symmetric_difference. It adds elements to the linked set that are only in the argument and removes elements that are in both sets:

a, b = {1, 2}, {2, 3}
a.symmetric_difference_update(b)
a  # {1, 3}

The update method

The update is the modifying equivalent of | or union. It complements the associated set with missing elements from the argument set:

a, b = {1, 2}, {2, 3}
a.update(b)
a  # {1, 2, 3}

Concerning uniformity, the update should have been called union_update. But we chose the more common name update because developers often use this name for similar methods in other collections.