Python Set update() method



The Python Set update() method is used with sets to modify the set by adding elements from another iterable or set. It takes an iterable such as another set, list or tuple as an argument and adds its elements to the calling set. If any element in the iterable is already present in the set it won't be added again.

This method allows for the efficient merging of multiple sets or iterables into one by making it useful for combining data structures and eliminating duplicates. The original set is modified in place and the method returns None indicating that the set has been updated.

Syntax

Following is the syntax and parameters of Python Set update() method −

set.update(iterable)

Parameter

This method accepts an iterable such as a list, tuple or another set containing elements to be added to the set.

Return value

This method does not return any value.

Example 1

Following is the example which shows updating the original set with another set of elements −

# Define a set
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Update set1 with elements from set2
set1.update(set2)

print(set1)

Output

{1, 2, 3, 4, 5}

Example 2

This example shows how to update a set with elements of different types of iterables −

# Define a set
my_set = {1, 2, 3}
my_iterable = [3, (4, 5), 6]

# Update the set with elements from the iterable
my_set.update(my_iterable)

print(my_set) 

Output

{1, 2, 3, 6, (4, 5)}

Example 3

This example shows how to update a set with elements from nested sets −

# Define a set
my_set = {1, 2}
nested_set = {3, 4, (5, 6), 7 , 8}

# Update the set with elements from the nested set
my_set.update(nested_set)

print(my_set)  

Output

{1, 2, 3, 4, (5, 6), 7, 8}

Example 4

In this example we are updating with an empty iterable which does not change the set −

# Define a set
my_set = {1, 2, 3}
empty_iterable = []

# Update the set with an empty iterable
my_set.update(empty_iterable)

print(my_set)  

Output

{1, 2, 3}
python_set_methods.htm
Advertisements