Another commonly used data structure is the set, a collection of objects that support operations such as:
Make a new set with all items in common.
Make a new set with all items in either operand.
Test whether an item exists in a set.
Other operations, such as difference and subset tests, can be useful as well, depending on the intended use. Sets come in handy for dealing with abstract group combinations. For instance, given a set of engineers and a set of writers, you can pick out individuals who do both activities by intersecting the two sets. A union of such sets would contain either type of individual, but would include any given individual only once. This latter property also makes sets ideal for removing duplicates from collections—simply convert to and from a set to filter out repeats.
In fact, we relied on such operations in earlier chapters; PyMailGUI in Chapter 14, for example, used intersection, union, and difference to manage the set of active mail downloads, and filtered out duplicate recipients in multiple contexts with set conversion. Sets are a widely relevant tool on practical programs.
If you’ve studied the core Python language, you should already know that, as for stacks, Python comes with built-in support here as well. Here, though, the support is even more direct—Python’s set datatype provides standard and optimized set operations today. As a quick review, built-in set usage is straightforward: set objects ...