Python set Method - update()
The update()
method in Python sets updates the set calling the method with the union of itself and another set. In other words, it adds all elements from another set that are not already in the set.
The syntax for the update()
method is as follows:
set1.update(set2)
Here, set1
is the set for which we want to update with the union, and set2
is the other set.
Example:
# Creating two sets set1 = {1, 2, 3} set2 = {3, 4, 5} # Updating set1 with the union of set1 and set2 set1.update(set2) print(set1) # Output: {1, 2, 3, 4, 5}
In the above example, the update()
method is used to update set1
with the union of set1
and set2
. Since set1
contains the elements 1
, 2
, and 3
, and set2
contains the elements 3
, 4
, and 5
, the union of the two sets is the set of all elements that are present in either of the sets, which is {1, 2, 3, 4, 5}
. After calling the update()
method, set1
is updated with the union, which is {1, 2, 3, 4, 5}
. The updated set is printed using the print()
function. Note that the elements 3
is included only once in the updated set, since sets do not allow duplicates.