Python Set update()

The update() adds elements from a set (passed as an argument) to the set (calling the update() method).

The syntax of update() is:

A.update(B)

Here, A and B are two sets. The elements of set B are added to the set A.


update() Parameters

The update() method takes a single argument (a set).

If you need to add elements of other native datatypes (like tuple, list, dictionary etc.) to the set, you can simply use:

# add list elements to set
set.update(set(list))

or even easier

set.update(list)

Return Value from update()

The A.update(B) adds elements from the set B to A.

This method returns None (meaning, absence of a return value).


Example 1: How update() works in Python?

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

result = A.update(B)
print('A =',A)
print('B =',B)
print('result =',result)

When you run the program, the output will be:

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

Example 2: Adding Elements of String and Dictionary to Set

# Update With String
string_alphabet = 'abc'
numbers_set = {1, 2}

numbers_set.update(string_alphabet)

print('numbers_set =',numbers_set)
print('string_alphabet =',string_alphabet)

# Update With Dictionary
info_dictionary = {'key': 1, 2 : 'lock'}
numbers_set = {'a', 'b'}

numbers_set.update(info_dictionary)
print('numbers_set =',numbers_set)

When you run the program, the output will be:

numbers_set = {'c', 1, 2, 'b', 'a'}
string_alphabet = abc
numbers_set = {'key', 'b', 2, 'a'}