Python Set update() Method

Updates the set by adding items from all the specified sets

Usage

The update() method updates the original set by adding items from all the specified sets, with no duplicates.

You can specify as many sets as you want, just separate each set with a comma.

If you don’t want to update the original set, use union() method.

Syntax

set.update(set1,set2…)

Python set update() method parameters
ParameterConditionDescription
set1, set2…OptionalA comma-separated list of one or more sets to merge with.

Basic Example

Example: Update the set by adding items from other set

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A.update(B)
print(A)

Output:

{'blue', 'green', 'yellow', 'orange', 'red'}

Venn Diagram:

Set union

Equivalent Operator |=

You can achieve the same result by using the |= augmented assignment operator.

Example:

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A |= B
print(A)

Output:

{'blue', 'green', 'yellow', 'orange', 'red'}

Update() Method with Multiple Sets

Multiple sets can be specified with either the operator or the method.

Example:

# by method
A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

A.update(B,C)
print(A)
# by operator
A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

A |= B | C
print(A)

Output:

{'blue', 'green', 'yellow', 'orange', 'black', 'red'}