Python Set update() Method

Python Set update() method is “used to add elements from a set (passed as an argument) to the set.

Syntax

set1.update(set2)

Parameters

set2: The method takes a set2 as an argument, and set1 will be updated with set2. But we can update a set with another native data type (like tuple, list, etc.).

set_name.update(set(native_datatype_name)) 

Return Value

The update() method returns None. It just updates the value of the set.

Example 1: How to Use Set update() Method

# 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 after adding north indian states ", country)
country.update(sstate)
print("States in country after adding north indian states ", country)

Output

North states are: {'Kashmir', 'Himachal Pradesh', 'Punjab', 'Uttarakhand'}
South states are: {'Andhra Pradesh', 'Kerala', 'Tamil Nadu', 'Telangana'}

States in country after adding north indian states 
          {'Kashmir', 'Himachal Pradesh', 'Punjab', 'Uttarakhand'}
States in country after adding north indian states 
          {'Himachal Pradesh', 'Telangana', 'Andhra Pradesh', 'Punjab', 
          'Kerala', 'Tamil Nadu', 'Uttarakhand', 'Kashmir'}

Example 2: Working with an empty set

# Name of flowers in a list
flower = ['rose', 'tulip', 'poppy']

# Name of fruits in a tuple
fruits = ('apple', 'banana', 'orange')

print("Flowers are: ", flower)
print("Fruits are: ", fruits)

# declaring new empty set
mix = set()

# Now we will update these values in set mix
mix.update(list(flower))
print("After adding flowers elements in mix are: ", mix)
mix.update(tuple(fruits))
print("After adding fruits elements in mix are: ", mix)

Output

Flowers are: ['rose', 'tulip', 'poppy']
Fruits are: ('apple', 'banana', 'orange')
After adding flowers elements in mix are: {'poppy', 'tulip', 'rose'}
After adding fruits elements in mix are: {'orange', 'rose', 'poppy', 
                                         'banana', 'tulip', 'apple'}

Example 3: Python set update element in the set

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, 'a', 'b', 'c'}

That’s it!

Related posts

Python Set add()

Python Set intersection_update()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.