Python set update() Method

set.update(*iterables) adds the elements produced by one or more iterables to an existing set and returns None. Duplicate values are stored only once.

Because a set is mutable, update() changes it in place. Use add() when you want to add one hashable object as a single element.

Set order: sets are unordered. Whenever an example prints a set, the displayed element order can differ between runs or Python environments.
my_set={'a','b','c','x'}
my_set2={'x','y','z'}
my_set.update(my_set2)
print(my_set)
Output is here
{'z', 'a', 'x', 'y', 'b', 'c'}
In above code x is added once only as no duplicate value is kept.

Adding a string

In python string is a iterable object
my_set={'a','b','c','x'}
text='alex'
my_set.update(text)
print(my_set)
Output
{'a', 'b', 'c', 'x', 'l', 'e'}

Adding a list

More on list
my_set={'a','b','c','x'}
my_list=['x','y','z']
my_set.update(my_list)
print(my_set)
Output
{'z', 'a', 'y', 'b', 'x', 'c'}

Adding a tuple

More on tuple
my_set={'a','b','c','x'}
my_tuple=('x','y','z')
my_set.update(my_tuple)
print(my_set)
Output
{'z', 'a', 'y', 'b', 'x', 'c'}
Values already present are not duplicated; a set stores each distinct value only once.

Difference between add() and update()

Use add() to add one hashable object as a single element. Use update() to consume the elements of one or more iterables such as a list, tuple or string.
All Set Methods Questions with solutions on set


Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer