Tutorial Study Image

Python update()

The update() function in python helps to update the set by adding elements from another set, that is from given iterable. If the same element is present in both the set, only one occurance is placed.


A.update(iterable) #where iterable such as list, set, dictionary, string, etc.
 

update() Parameters:

The update() function takes a iterable parameter. If the given iterable is a list, tuples, or a dictionary this function will automatically convert it into a set and add the elements to the set.

Parameter Description Required / Optional
Iterable The iterable insert into the current set Required

update() Return Value 

The update() function doesn't return any value, it just updates the existing set by adding elements into it. This function can accept multiple iterable parameters separated by commas.   

Examples of update() method in Python

Example 1: How Python set update() works?


X = {'x', 'y'}
Y = {5, 4, 6}

result = X.update(Y)

print('X =', X)
print('result =', result)
 

Output:


A = {'x', 5, 4, 6, 'y'}
result = None

Example 2: How to add elements of string and dictionary to Set using update()?


alphabet_str = 'abc'
num_set = {1, 2}

# add elements of the string to the set
num_set.update(alphabet_str)

print('Numbers Set =', num_set)

dict_info= {'key': 1, 'lock' : 2}
num_set = {'a', 'b'}

# add keys of dictionary to the set
num_set.update(dict_info)
print('Numbers Set=', num_set)
 

Output:


Numbers Set = {'c', 1, 2, 'b', 'a'}
Numbers Set = {'key', 'b', 'lock', 'a'}