The update method
The update
method adds elements from other sets to one set. This changes the original set, and the method itself does not return anything. In the method parameter, we specify the sets whose elements we want to add.
Syntax
set.update(sets we want to add)
Example
Let's use the update
method to add elements to our set:
st1 = {'a', 'b', 'c'}
st2 = {'1', '2', '3'}
st1.update(st2)
print(st1)
Result of code execution:
{'1', 'a', '2', '3', 'b', 'c'}
Example
The update
method also has a short form:
st1 = {'a', 'b', 'c'}
st2 = {'1', '2', '3'}
st1 |= st2
print(st1)
Result of code execution:
{'1', '3', 'b', 'a', 'c', '2'}
Example
Now let's add elements from two lists to our set:
st1 = {'a', 'b', 'c'}
st2 = {'1', '2', '3'}
st3 = {5, 10, 15}
st1.update(st2, st3)
print(st1)
Result of code execution:
{'a', 'b', 5, '2', 10, '3', '1', 15, 'c'}
Example
Let's rewrite the previous example in a short form:
st1 = {'a', 'b', 'c'}
st2 = {'1', '2', '3'}
st3 = {5, 10, 15}
st1 |= st2 | st3
print(st1)
Result of code execution:
{'b', 5, 'c', 10, 15, '3', '2', '1', 'a'}