set union
A set union is the operation that combines two or more sets into a single set containing every element that appears in at least one of them. Formally, the union of two sets A and B, written A ∪ B, is the set of all values that belong to A or to B, with elements that appear in both counted only once:
This deduplication follows from the fact that a set holds no repeated elements. Union is commutative and associative, so the order and grouping of the inputs never change the outcome. The empty set is the identity element for union, since uniting any set with it leaves the set unchanged.
The operation generalizes beyond two inputs. An n-ary union combines a finite list of sets, and an indexed union combines an arbitrary family of them.
When each set is stored as a hash table, computing the union of two sets takes time proportional to their combined size. Python exposes union on its built-in set type through the | operator and the .union() method, each returning a new set.
Related Resources
Tutorial
Sets in Python
Learn how to work effectively with Python sets. You’ll define set objects, explore supported operations, and understand when sets are the right choice for your code.
For additional information on related topics, take a look at the following resources:
- Python Set Comprehensions: How and When to Use Them (Tutorial)
- Common Python Data Structures (Guide) (Tutorial)
- Build a Hash Table in Python With TDD (Tutorial)
- Using Sets in Python (Course)
- Python Sets (Quiz)
- Python Set Comprehensions: How and When to Use Them (Quiz)
- Stacks and Queues: Selecting the Ideal Data Structure (Course)
- Records and Sets: Selecting the Ideal Data Structure (Course)
- Dictionaries and Arrays: Selecting the Ideal Data Structure (Course)
- Build a Hash Table in Python With TDD (Quiz)