Python Set update() Method

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

Visual Representation of How to Use Python Set update() Method

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

Visual Representation of 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 add()

Python Set intersection_update()

Leave a Comment

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