Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
python3
sets
communitycreator

How does set update() work in Python?

Hassan Ahmed

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))

RELATED TAGS

python
python3
sets
communitycreator
RELATED COURSES

View all Courses

Keep Exploring