Python Set update() Method (with Examples)

Python Set update() Method: In this tutorial, we will learn about the update() method of the set class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 14, 2023

Python Set update() Method

The update() is an inbuilt method of the set class that is used to update this set (set1) by adding more elements of another set (set2), the method is called with this set (set1) and another set (set2) can be supplied as an argument, the first set (i.e., this set) is updated with the elements of another set (set2). Note: Similar elements will not be updated.

Syntax

The following is the syntax of update() method:

set1.update(set2)

Parameter(s):

The following are the parameter(s):

  • set2 – It represents another set whose elements to be added in set1.

Return Value

The return type of this method is <class 'NoneType'>, it returns nothing.

Example 1: Use of Set update() Method

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# printing the set before update() call
print("Printing the sets before update() call...")
print("cars_1: ", cars_1)
print("cars_2: ", cars_2)

# updating set (cars_1) by adding 
# the elements of cars_2 elements
cars_1.update(cars_2)

# printing the set after update() call
print("Printing the sets after update() call...")
print("cars_1: ", cars_1)
print("cars_2: ", cars_2)

Output

Printing the sets before update() call...
cars_1:  {'Porsche', 'Lexus', 'Audi'}
cars_2:  {'Porsche', 'Mazda', 'Lincoln'}
Printing the sets after update() call...
cars_1:  {'Porsche', 'Audi', 'Mazda', 'Lincoln', 'Lexus'}
cars_2:  {'Porsche', 'Mazda', 'Lincoln'}

Example 2: Use of Set update() Method

# Python Set update() Method (with Examples)

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "ABC"}

# printing the sets before update() call
print("Before calling update()...")
print("x:", x)
print("y:", y)
print("z:", z)

# Updating the set with other set's elements
x.update(y)
y.update(z)
z.update(x)

# printing the sets after update() call
print("After calling update()...")
print("x:", x)
print("y:", y)
print("z:", z)

Output

Before calling update()...
x: {'XYZ', 'ABC', 'PQR'}
y: {'XYZ', 'ABC', 'PQR'}
z: {'MNO', 'ABC', 'DEF'}
After calling update()...
x: {'ABC', 'PQR', 'XYZ'}
y: {'ABC', 'PQR', 'XYZ', 'MNO', 'DEF'}
z: {'ABC', 'PQR', 'XYZ', 'MNO', 'DEF'}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.