Union of Sets in Python
The update method allows not only to add elements, but also to combine several sets.
Let us have two sets:
st1 = {'a', 'b', 'c', 'd'}
st2 = {1, 2, 3, 4}
Let's add the second set to the first:
st1.update(st2)
And then we output the first set to the console:
print(st1) # {'c', 1, 2, 3, 4, 'b', 'd', 'a'}
You can also pass multiple sets to the update method. Let's create a third set:
st3 = {'x', 'y', 'z'}
Now let's add the second and third sets to the first:
st1.update(st2, st3)
Let's output the first set to the console:
print(st1) # {1, 2, 3, 4, 'd', 'y', 'x', 'c', 'a', 'b', 'z'}
The union of sets can be written in a more concise form using the operator |. Let's rewrite the previous example in a concise form:
st1 = st2 | st3
Two sets are given:
st1 = {'a', 'b', 'c', 'd', 'e'}
st2 = {'d', 'e', 'f', 'g', 'h'}
Combine these sets into one.
Three sets are given:
st1 = {'2', '4', '6'}
st2 = {7, 8, 9}
st3 = {'1', '3', '4'}
Combine these sets into one.
Given sets:
st1 = {1, 2, 3}
st2 = {'a', 'b', 'c'}
st3 = {4, 5, 6}
st4 = {'d', 'e', 'f'}
Combine the first and third sets, then the second and fourth sets in a short form. Output the result to the console.