Operators with Sets

Operators offer a variety of valuable ways to manipulate sets, with many of these operations rooted in set theory. For those interested in a deeper understanding of these concepts, the linked Wikipedia article is a great resource, though the examples provided here should also help to clarify their meaning and application. In this lesson we will learn the set operations: union, intersection, difference, and symmetric difference. Mastering these set manipulations can lead to some very elegant solutions in software engineering!

Throughout the examples in this lesson, we will use three sets: A, B, and C, as illustrated in the code area below.

Set union with |

Set union: The union of two sets includes all the unique elements found in either set. If an element is in either of the sets (or in both), it will be in the union of the sets.

Set intersection with &

The set intersection of two sets includes only the elements that are found in both sets. If an element is in one set but not the other, it will not be in the intersection.

Set difference with -

The set difference between two sets A and B includes the elements that are in A but not in B. It essentially "subtracts" the elements of B from A. We can also look at the reverse relationship of B - A, which would include the elements that are in B but not in A.

Set symmetric difference with ^

The set symmetric difference between two sets includes the elements that are in either of the sets, but not in both. It is like the union of the sets, but excluding the intersection.

Subset with < and <=

Any set is considered a subset of another if every element of it is also an element of the other.

Operations with dictionaries

While dictionaries in Python are not inherently designed for set operations in the same way that sets are, certain operations can still be applied. For instance, the union operator can be utilized to merge two dictionaries, effectively taking the union of their keys. If there are overlapping keys, the values from the second dictionary will prevail. Additionally, the equality operator we learned a few lessons ago can be used to check whether two dictionaries are identical, comparing both keys and associated values for exact matches.

Practice Question

For each question, select the set that matches the operation. Use the sets below for the questions.

Q01

Q02

Q03

score: 0%