Python Set | update()
Python update() function in set adds elements from a set (passed as an argument) to the set.
Syntax : set1.update(set2)
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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.
Example of Python set update()
Example 1: Working with Python set update list
Python3
# Python program to demonstrate the# use of update() methodlist1 = [1, 2, 3]list2 = [5, 6, 7]list3 = [10, 11, 12]# Lists converted to setsset1 = set(list2)set2 = set(list1)# Update methodset1.update(set2)# Print the updated setprint(set1)# List is passed as an parameter which# gets automatically converted to a setset1.update(list3)print(set1) |
Output :
{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7, 10, 11, 12}Example 2: Python set update element in set
Python3
# Python program to demonstrate the# use of update() methodlist1 = [1, 2, 3, 4]list2 = [1, 4, 2, 3, 5]alphabet_set = {'a', 'b', 'c'}# lists converted to setsset1 = set(list2)set2 = set(list1)# Update methodset1.update(set2)# Print the updated setprint(set1)set1.update(alphabet_set)print(set1) |
Output :
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 'c', 'b', 'a'}Example 3: Add elements of the dictionary to Set
Python3
number = {1, 2, 3, 4, 5}num_Dict = {6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten'}number.update(num_Dict)print("Updated set: ", number) |
Output:
Updated set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
