Python Set update():
The update() method adds an element set passed to the existing set.
Method signature
The signature for the update() method is as shown below. Here, s1 is a destination set where it adds the element from a set s2.
s1.update(s2)
Method parameters and return type
- The update() method takes only one parameter. This parameter can be a data element, set, list, tuple, or dictionary.
- However, this method doesn’t return anything.
Python Set Update Examples:
Example 1: In this example, let us take a set s1 and set s2 with a set of numbers.
#Initializing the Set
s1={8,311,98,36,15}
s2={6,55,32}
#Printing a result
print("Before update s1 is ",s1)
# Performing update
s1.update(s2)
#Printing a result
print("After update s1 is ",s1)
Output
Before update s1 is {98, 36, 8, 15, 311}
After update s1 is {32, 98, 36, 6, 8, 15, 55, 311}
Example 2: For this example, let us take a set containing an employee’s record as “e1”. Later, If we want to add the other details such as project manager and department stored in set “p1” then we can use the update method to add those details.
#Initializing the Set
e1={"Raj","E223","Hyderabad"}
p1={"Philip","Network Security" }
#Printing a set
print("Before update",e1)
#Using update method
e1.update(p1)
#Printing a set
print("After update",e1)
Output
Before update {'Raj', 'E223', 'Hyderabad'}
After update {'E223', 'Raj', 'Network Security', 'Philip', 'Hyderabad'}
Example 3: In this example, let us demonstrate the update() method using a tuple, list and dictionary.
#Initializing the Set
s1={10,20,30}
#Initializing the list, tuple and dictionary
l1=[12,34,22]
t1=(55,65,85)
d1={"Name":"John","Salary":50000,"Experience":10}
#Using update method and printing after each update
s1.update(l1)
print("Set with data from list",s1)
s1.update(t1)
print("Set with data from list and tuple",s1)
s1.update(d1)
print("Set with data from list, tuple and dictionary",s1)
Output
Set with data from list {34, 10, 12, 20, 22, 30}
Set with data from list and tuple {65, 34, 10, 12, 20, 85, 22, 55, 30}
Set with data from list, tuple and dictionary {65, 34, 'Salary', 10, 12, 20, 85, 22, 55, 'Name', 'Experience', 30}
Conclusion
The update() method updates the original data by adding the element from the parameter passed.
References
Happy Learning 🙂