update() method for set

All set methods

update(set) takes one set arguments .

set : set to be added to main set
While adding using update we can add iterable objects like string , list etc Returns : No return value.
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'}
str='alex'
my_set.update(str)
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'}
There is no error if we try to add element already available but it will not update the element again as set can't have duplicate elements.

Difference between add() and update()

By using add() method we can add one element only, by using update() we can add more elements.
By using add() we can't add iterable objects , by using update we can add elements of iterable objects like list.
All set methods Questions with solutions on set

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    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 FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer