Python – Join Sets
Python offers a robust set of methods for performing operations on multiple sets. These include union(), update(), intersection(), difference(), and symmetric_difference(). Each method has its unique application depending on the desired outcome when working with set data structures.
1. Union of Sets
The union() method creates a new set containing all unique elements from the involved sets.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Alternatively, you can use the | operator:
set3 = set1 | set2
print(set3)
Joining Multiple Sets
You can pass multiple sets to the union() method by separating them with commas:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
result = set1.union(set2, set3, set4)
print(result)
Using | for multiple sets:
result = set1 | set2 | set3 | set4
print(result)
Union with Other Data Types
The union() method supports merging with tuples or lists:
x = {"a", "b", "c"}
y = (1, 2, 3)
z = x.union(y)
print(z)
Note: The | operator does not support other data types.
2. Update Method
update() merges elements from one set into another, modifying the original set.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Note: Duplicate values are automatically excluded.
3. Intersection of Sets
intersection() returns a new set containing only elements that appear in all involved sets.
