Python - Set update() Method

Advertisements

The Python set update() method is used to add elements in a set which in not present in the set but present in the specified sets or iterables. This method can take any number of sets or iterables to update the original set.

The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {50, 60, 70, 80}. As the union set contains all elements of the two given sets, hence the union of these sets will be {10, 20, 30, 40, 50, 60, 70, 80}. The update() method can be expressed as:

• A.update(B) is same as A = AUB
• B.update(A) is same as B = BUA
• A.update(B, C) is same as A = AUBUC

Syntax

set.update(iterable(s))


Parameters

 iterable(s) Optional. specify set(s) or iterable(s) to update the given set.

Example: Update set using set as an argument

In the below example, two sets called SetA and SetB are taken and SetA is updated with SetB elements using python update() method.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {50, 60, 70, 80}

SetA.update(SetB)
print(SetA)


Output

{10, 20, 30, 40, 50, 60, 70, 80}


Example: Update set using set and iterable as arguments

The update() method can take any numbers of sets or iterables to update the given set. In the below example, the update() method is used with SetB and ListC to update SetA.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {40, 50, 90}
ListC = [40, 90, 100]

SetA.update(SetB, ListC)
print(SetA)


Output

{10, 20, 30, 40, 50, 60, 90, 100}


Advertisements