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

# Update the set by adding items from other set
A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A.update(B)
print(A)
# Prints {'blue', 'green', 'yellow', 'orange', 'red'}
Set union

Equivalent Operator |=

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

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

A |= B
print(A)
# Prints {'blue', 'green', 'yellow', 'orange', 'red'}

Update() Method with Multiple Sets

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

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

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

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