Python Set | update()
update() function in set adds elements from a set (passed as an argument) to the set.
Syntax :
set1.update(set2)
Here set1 is the set in which set2 will be added.Parameters :
Update() method takes only a single argument. The single argument can be a set, list, tuples or a dictionary. It automatically converts into a set and adds to the set.
Return value : This method adds set2 to set1 and returns nothing.
Code #1 :
# Python program to demonstrate the # use of update() method list1 = [1, 2, 3] list2 = [5, 6, 7] list3 = [10, 11, 12] # Lists converted to sets set1 = set(list2) set2 = set(list1) # Update method set1.update(set2) # Print the updated set print(set1) # List is passed as an parameter which # gets automatically converted to a set set1.update(list3) print(set1) |
Output :
{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7, 10, 11, 12}
Code #2 :
# Python program to demonstrate the # use of update() method list1 = [1, 2, 3, 4] list2 = [1, 4, 2, 3, 5] alphabet_set = {'a', 'b', 'c'} # lists converted to sets set1 = set(list2) set2 = set(list1) # Update method set1.update(set2) # Print the updated set print(set1) set1.update(alphabet_set) print(set1) |
Output :
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 'c', 'b', 'a'}
Recommended Posts:
- Set update() in Python to do union of n arrays
- Python | Pandas Series.update()
- Python Dictionary | update() method
- MongoDB Python | Insert and Update Data
- Dictionary Methods in Python | Set 2 (update(), has_key(), fromkeys()...)
- Python | Update a list of tuples using another list
- Python | Merge Python key values to list
- Python | Index of Non-Zero elements in Python list
- Important differences between Python 2.x and Python 3.x with examples
- Reading Python File-Like Objects from C | Python
- Python | Convert list to Python array
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



