Python - Set Operations
Code Life
By Pierre Marsaa
Introduction to Set Union
Sets can be combined using various operations. One of the most common operations is the union.
The union operation combines all elements from two or more sets. It creates a new set containing every unique element from all sets involved.
source
In Python, you can perform union in two ways:
- Using the | operator
- Using the .union() method
↗️
Loading editor...
↶
↷
Notice how the union contains all Codémon from both sets, with no duplicates. The order may vary since sets are unordered.
Union with Duplicates
If the same element exists in both sets, it appears only once in the union. For example, if {'A', 'B'} | {'B', 'C'}, the result is {'A', 'B', 'C'} - B appears only once even though it's in both sets.
Verify