Python Set update() Method

The set.update() method updates the set by adding distinct elements from the passed one or more iterables.

Syntax:

set.update(iterable)

Parameters:

iterable: The iterable to be added to the set.

Return type:

No return value.

The following example demonstrates the set.update() method.

Example: Update Set
nums = {1, 2, 3}
primeNums = {2, 3, 5, 7}

nums.update(primeNums)
print("Updated set: ", nums)
Output
Updated set:  {1, 2, 3, 5, 7}

Update a Set from Multiple Sets

The set.update() method can accept multiple iterables as arguments.

Example: Update Set
nums = { 1, 2, 3 }
evenNums = { 2, 4, 6 }
primeNums = { 5, 7 }
nums.update(evenNums, primeNums)

print("Updated set: ", nums)
Output
Updated se:  { 1, 2, 3, 4, 5, 6, 7 }

Update a Set using the | Operator

The |symbol can also be used to update a set from another set, instead of the update() method, as shown below.

Example: The | Operator
nums = { 1, 2, 3 }
evenNums = { 2, 4, 6 }
primeNums = { 5, 7 }

nums = nums | evenNums | primeNums
print("Updated set: ", nums)
Output
Updated se:  { 1, 2, 3, 4, 5, 6, 7 }

Update a Set from List, Tuple

The set.update() method also works any other iterables list, tuple, dictionary, as shown below. Note that the | operator will only work with updating set from other sets but not other types of iterable.

Example: Update Other Iterables
nums = {1, 2, 3}
oddNums = [1, 3, 5, 7, 9]
evenNums = (2, 4, 6, 8, 10)

nums.update(oddNums) # adding list elements
print("Updated set: ", nums)

nums.update(evenNums) # adding tuple elements
print("Updated set: ", nums)

# nums = nums | evenNums # throws error
Output
Updated set:  {1, 2, 3, 5, 7, 9}
Updated set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Update a Set from Dictionary

When a dictionary is passed as an argument, the set gets updated with the keys of the dictionary.

Example:
nums = {1,2,3,4,5}
numsDict = {6:'Six',7:'Seven',8:'Eight',9:'Nine',10:'Ten'}
nums.update(numsDict)
print("Updated set: ", nums)
Output
Updated set:  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}