Python Set update()

In this tutorial, you will learn about the Python Set update() method with the help of examples.


A = {'a', 'b'}
B = {1, 2, 3}

# updates A after the items of B is added to A A.update(B)
print(A) # Output: {'a', 1, 2, 'b', 3}

update() Syntax

The syntax of the update() method is:


Here, A is a set and B can be any iterable like list, set, dictionary, string, etc.

update() Parameter

The update() method can take any number of arguments. For example,

A.update(B, C, D)


  • B, C, D - iterables whose items are added to set A

update() Return Value

The update() method doesn't return any value.

Example 1: Python Set update()

A = {1, 3, 5}
B = {2, 4, 6}
C = {0}

print('Original A:', A)

# adds items of B and C to A and updates A A.update(B, C)
print('A after update()', A)


Original A: {1, 3, 5}
A after update() {0, 1, 2, 3, 4, 5, 6}

In the above example, we have used the update() method to add items of set B and C to A and update A with the resulting set.

Here, initially set A only has 3 items. When we call update(), the items of B and C are added to set A.

Example 2: update() to add String and Dictionary to Set

# string
alphabet = 'odd'

# sets
number1 = {1, 3}
number2 = {2, 4}

# add elements of the string to the set number1.update(alphabet)
print('Set and strings:', number1) # dictionary key_value = {'key': 1, 'lock' : 2}
# add keys of dictionary to the set number2.update(key_value)
print('Set and dictionary keys:', number2)


Set and strings: {1, 3, 'o', 'd'}
Set and dictionary keys: {'lock', 2, 4, 'key'}

In the above example, we have used the update() method to add string and dictionary to the set.

The method breaks down the string into individual characters and adds them to the set number1. Similarly, it adds the keys of the dictionary to the set number2.

Note: If dictionaries are passed to the update() method, the keys of the dictionaries are added to the set.

Did you find this article helpful?