Python Set – update() method

It is a method in python set that add items from other iterables such as set, list, string etc to the parent set, thus updating the current set. add() method cannot take multiple iterables but update() can. It doesn’t return any value. And it modifies the given set.

Syntax:
set.update(iterables)

Example 1:

# Python code to understand update() method in set
# www.codewindow.in

s = {"amazing", "code"}
s1 = {"window", "hustle"}
s.update(s1)
print(s)

Output:

{'window', 'code', 'hustle', 'amazing'}

Explanation:
Here all the iterables in the set s1 are updated to the parent set (s).

Example 2:

# Python code to understand update() method in set
# www.codewindow.in

s = {5, 8, 4}
s1 = "code"
s.update(s1)
print(s)

Output:

{4, 5, 'c', 8, 'd', 'e', 'o'}

Explanation:
Here all the iterables in the string s1 are updated to the parent set (s).

Example 3:

# Python code to understand update() method in set
# www.codewindow.in

s = {5, 8, 4}
s1 = {"code":1, "search":2}
s.update(s1)
print(s)

Output:

{4, 5, 'code', 8, 'search'}

Explanation:
Here all the keys of the dictionary are updated to the parent set.
Note: if a dictionary is used as an iterable, the keys gets updated to the set, not the values.

Example 4:

# Python code to understand update() method in set
# www.codewindow.in

s = {"amazing", "code"}
s1 = {"window", "hustle"}
s2 = {"best"}
s.update(s1,s2)
print(s)

Output:

{'window', 'amazing', 'best', 'code', 'hustle'}

Explanation:
Here all the iterables in the set s1 and s2 are updated to the parent set (s). Thus it can take multiple iterables.


You missed

Also Checkout