The Set update() method accepts another iterable such as Set, List, String, Dictionary as a parameter and adds the elements of these iterable to the calling set. This method converts the passed iterable to the set before adding their elements to the calling Set. For example – Lets say we have a Set A: {1, 2, 3} and a List lis: [2, “hello”] then calling A.update(lis) would update the set A and the elements of set A after update would be {1, 2, 3, “hello”}.
Set update() method Syntax
set.update(iterable)
Parameters: This method accepts iterable (list, tuple, dictionary etc.) as parameters.
Return Value: It does not return anything, it just updates the calling Set.
Python Set update() method example
In the following example we have two Sets of numbers X & Y and we are calling X.update(Y) to add the elements of set Y to the Set X.
# Set X X = {1, 2, 3} # Set Y Y = {2, 3, 4} # Displaying X & Y before update() print("X is:",X) print("Y is:",Y) # Calling update() method X.update(Y) # Displaying X & Y after update() print("X is:",X) print("Y is:",Y)
Output:
Set update() method example with List, Tuple, String, Dictionary
In the following example we are adding the elements of a list, tuple, string & dictionary to the calling set X using the update() method.
# Set X X = {1, 2, 3} # List lis lis = [3, 5] # tuple t = (77, 99) # String s = "abc" # Dictionary dict dict = {"one": 1, "two": 2} # Calling update() method X.update(lis, t, s, dict) # Displaying X after update() print("X is:",X)
Output:
Leave a Reply