The Set update() method adds elements from another set (or any other iterable) to the current set, without duplicates.
Syntax
my_set.update(set1, set2, ...)update() Parameters
Python Set update() method parameters:
| Parameter | Condition | Description |
|---|---|---|
set1, set2, ... |
Optional | A comma-separated list of one or more sets to merge with |
update() Return Value
Python Set update() method does not return any values: it modifies the set in place by adding elements from another set (or any other iterable), without duplicates.
Examples
Example 1: Update of Two Sets with update() method
A = {'Tom', 'Anna'}
B = {'David', 'Ryan'}
A.update(B)
print(A) # Output: {'David', 'Ryan', 'Anna', 'Tom'}output
{'David', 'Ryan', 'Anna', 'Tom'}Example 2: Update between Multiple Sets
The update() method allows to adding elements from multiple sets, without duplicates:
A = {1, 2, 3}
B = {3, 4, 5, 6, 7}
C = {6, 7, 8, 9, 10}
A.update(B, C)
print(A) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}output
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}Example 3: Update between a Set and a List
You can also pass iterables like list: update() first converts the iterables to sets and then adds elements.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = ['d', 'e', 'f']
A.update(B)
print(A) # Output: {'a', 'i', 'u', 'f', 'e', 'd', 'o'}output
{'a', 'i', 'u', 'f', 'e', 'd', 'o'}Example 4: Update between a Set and a Tuple
You can also pass iterables like tuple: update() first converts the iterables to sets and then adds elements.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = ('d', 'e', 'f')
A.update(B)
print(A) # Output: {'a', 'i', 'u', 'f', 'e', 'd', 'o'}output
{'a', 'i', 'u', 'f', 'e', 'd', 'o'}Example 5: Update between a Set and a Dictionary
You can also pass iterables like dictionary: update() first converts the iterables to sets and then adds elements.
For example:
A1 = {'a', 'e', 'i', 'o', 'u'}
A2 = {'a', 'e', 'i', 'o', 'u'}
B = {1: 'd', 2: 'e', 3: 'f'}
C = {'d': 1, 'e': 2, 'f': 3}
A1.update(B)
A2.update(C)
print(A1) # Output: {1, 2, 3, 'a', 'e', 'o', 'i', 'u'}
print(A2) # Output: {'a', 'e', 'f', 'o', 'd', 'i', 'u'}output
{1, 2, 3, 'a', 'e', 'o', 'i', 'u'}
{'a', 'e', 'f', 'o', 'd', 'i', 'u'}Example 6: Update between a Set and a String
You can also pass iterables like string: update() first converts the iterables to sets and then adds elements.
For example:
A = {'a', 'e', 'i', 'o', 'u'}
B = 'def'
A.update(B)
print(A) # Output: {'a', 'i', 'u', 'o', 'e'}output
{'a', 'i', 'u', 'o', 'e'}Equivalent Operator |= for update()
Set Update can be performed with the |= operator as well, providing an alternative to the update() method.
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
A |= B
print(A) # Output: {1, 2, 3, 4, 5, 6, 7}output
{1, 2, 3, 4, 5, 6, 7}Moreover, you can use the |= operator with multiple sets:
A = {1, 2, 3}
B = {3, 4, 5, 6, 7}
C = {6, 7, 8, 9, 10}
A |= B | C
print(A) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}output
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}