Python Tutorial Python Advanced Python References Python Libraries

Python Set - update() Method



The Python 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
Union of Sets

Syntax

set.update(iterable(s))

Parameters

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

Return Value

None.

Example: Update set using set as an argument

In the example below, 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)

The output of the above code will be:

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

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 example below, 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)

The output of the above code will be:

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

❮ Python Set Methods