Python Set update() method is used to add multiple elements from an iterable (such as a list, tuple or another set) to the set.
Since sets do not allow duplicate values, any duplicates in the iterable are not added to the set.
Syntax
set1.update(set2)
Parameters
set2(required): It can be a set, list, tuple, or any other iterable that provides elements to be added to the set
Return Value
This method returns None. It just updates the value of the set.
Visual Representation
Example 1: How to Use Set update() Method
set1 = {1, 2, 3, 4}
set2 = {4, 5, 6, 7}
# Using set1.update() method
set1.update(set2)
print(set1)
Output
{1, 2, 3, 4, 5, 6, 7}
Example 2: Working with an empty set
# Set of North India States
nstate = {'Kashmir', 'Himachal Pradesh', 'Punjab', 'Uttarakhand'}
# Set of South Indian States
sstate = {'Kerala', 'Tamil Nadu', 'Andhra Pradesh', 'Telangana'}
print("North states are: ", nstate)
print("South states are: ", sstate)
# declaring an empty set
country = set()
# Now we will update country with those sets
country.update(nstate)
# Printing values
print("\nStates in country before adding south indian states ", country)
country.update(sstate)
print("States in country after adding south indian states ", country)
Output
North states are: {'Kashmir', 'Himachal Pradesh', 'Punjab', 'Uttarakhand'}
South states are: {'Andhra Pradesh', 'Kerala', 'Tamil Nadu', 'Telangana'}
States in country before adding south indian states
{'Kashmir', 'Himachal Pradesh', 'Punjab', 'Uttarakhand'}
States in country after adding south indian states
{'Himachal Pradesh', 'Telangana', 'Andhra Pradesh', 'Punjab',
'Kerala', 'Tamil Nadu', 'Uttarakhand', 'Kashmir'}
Example 3: Adding elements of a dictionary to set
info = {11, 21, 19, 18}
country = {1: 'Israel', 2: 'India', 3: 'USA'}
info.update(country)
print("Updated set: ", info)
Output
Updated set: {1, 18, 19, 2, 21, 3, 11}
Related posts
Python Set intersection_update()
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.