Python set Method - symmetric_difference_update()
The symmetric_difference_update()
method in Python sets updates the set calling the method with the symmetric difference of itself and another set. In other words, it removes all elements from the set that are in the other set and adds all elements from the other set that are not in the set.
The syntax for the symmetric_difference_update()
method is as follows:
set1.symmetric_difference_update(set2)
Here, set1
is the set for which we want to update with the symmetric difference, and set2
is the other set.
Example:
# Creating two sets set1 = {1, 2, 3} set2 = {2, 3, 4} # Updating set1 with the symmetric difference between set1 and set2 set1.symmetric_difference_update(set2) print(set1) # Output: {1, 4}
In the above example, the symmetric_difference_update()
method is used to update set1
with the symmetric difference between set1
and set2
. Since set1
contains the elements 1
, 2
, and 3
, and set2
contains the elements 2
, 3
, and 4
, the symmetric difference between the two sets is the set of all elements that are in exactly one of the sets, which is {1, 4}
. After calling the symmetric_difference_update()
method, set1
is updated with the symmetric difference, which is {1, 4}
. The updated set is printed using the print()
function.