EN
Python - join two sets
0
points
In this article, we would like to show you how to join two sets in Python.
1. Using union()
method
In this example, we use union()
method to create a new set with all items from the two existing sets.
my_set1 = {'A', 'B'}
my_set2 = {'C', 'D'}
my_set3 = my_set1.union(my_set2)
print(my_set3) # {'C', 'A', 'B', 'D'}
Output:
{'C', 'A', 'B', 'D'}
2. Using update()
method
In this example, we use update()
method to add the items from my_set2
to my_set1
.
my_set1 = {'A', 'B'}
my_set2 = {'C', 'D'}
my_set1.update(my_set2)
print(my_set1) # {'B', 'A', 'D', 'C'}
Output:
{'B', 'A', 'D', 'C'}
Note:
Both presented methods exclude duplicate elements.