Python set update method | Example code

Using Python set update() method updates you can add items from other iterables into a set. The update() method updates the current set, by adding items from another set or any other iterable object.

set.update(set) 

Note: this method takes only a single argument.

Python set update example

Simple example code updates a set1.

set1 = {'a', 'b'}
set2 = {1, 2, 3}

set1.update(set2)

print(set1)

Output:

Python set update method

Set update() method example with List, Tuple, String, Dictionary

# Set X
X = {1, 2, 3}

# List
lis = [3, 4]

# tuple
tup = (100, 200)

# String
s = "ABC"

# Dictionary dict
dict1 = {"one": 1, "two": 2}

# Calling update() method
X.update(lis, tup, s, dict1)

# Displaying set after update()
print(X)

Output: {1, 2, 3, 100, 4, ‘B’, ‘C’, 200, ‘two’, ‘one’, ‘A’}

Update a Set from Multiple Sets

nums = {1, 2, 3}
evenNums = {2, 4, 6}
primeNums = {5, 7}
nums.update(evenNums, primeNums)

print(nums)

Output: {1, 2, 3, 4, 5, 6, 7}

Do comment if you have any doubts and suggestions on this Python set topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.