In Python, a set is a group of elements that are unordered and do not contain duplicates. Although it may seem that the usefulness of this data structure is limited, it can actually be very helpful for organizing items and performing set mathematics.
For example, we can imagine two different groups of items that have some similarities and differences. Using set mathematics, we can find the matching items, differences, combine the sets based on different parameters, and more! This is especially helpful when combing through very large datasets.
Alternatively, there is also an immutable version of a set called a frozenset. A frozenset behaves similarly to a normal set, but it does not include methods that modify the frozenset in any way.
In this lesson, we’ll explore:
- How to create a set and a frozenset.
- How to add to a set (we won’t be able to mutate a frozenset).
- How to remove from a set (we won’t be able to mutate a frozenset).
- How to find specific elements in a set and a frozenset.
- How to perform set operations such as unions, intersections, and more.
Let’s jump in!
Examine the sample set visual. Notice that new elements have no trouble getting into a set, but existing elements cannot be added!