How does set update() work in Python?

The inbuilt update() method in Python is used to update the set that calls the method with items from other iterables, like lists and tuples.

Syntax

set1.update(iterable)

Parameters and return value

The update() method requires only one iterable to be passed as a parameter.

It is important to note that this method only returns None. Instead of a return value, the set that calls the method is simply updated with another iterable.

Example 1

#Updating a set with another set.
#Since the elements 'Dogs' and 'Seals' were already present
#in x, even in the updated set only one instance of these
#elements will remain.
x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
y = {'Dogs', 'Lions', 'Seals', 'Parrots'}
x.update(y)
print(x)

Example 2

#Updating x, with a tuple y
#x remains a set, even after being updated with a tuple
x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
y = ('Dogs', 'Lions', 'Seals', 'Parrots')
x.update(y)
print(x)
print(type(x))
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources