The update()
function in Python is a method for sets that updates the set by adding elements from another set or an iterable such as a list or tuple. It modifies the original set in place by adding all elements that are unique and not already present in the set.
Parameter Values
Parameter | Description |
---|---|
iterable | An |
Return Values
The update()
method returns None
; it updates the set in place.
How to Use update()
in Python
Example 1:
The update()
method updates the set with elements from another set or iterable.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 4, 5}
Example 2:
The update()
method can also take a list or tuple as an argument to update the set.
set1 = {1, 2, 3}
new_elements = [4, 5, 6]
set1.update(new_elements)
print(set1) # Output: {1, 2, 3, 4, 5, 6}
Example 3:
If the set is empty, the update()
method behaves similar to the add()
method.
empty_set = set()
empty_set.update([1, 2, 3])
print(empty_set) # Output: {1, 2, 3}