![]() |
VOOZH | about |
update() method add multiple elements to a set. It allows you to modify the set in place by adding elements from an iterable (like a list, tuple, dictionary, or another set). The method also ensures that duplicate elements are not added, as sets inherently only contain unique elements. Example:
{1, 2, 3, 4, 5}
set.update(*others)
Example 1: We can use update() to add all elements from one set to another. Any duplicate elements will be ignored.
{'a': 1, 'b': 3, 'c': 4}
Explanation: Since 3 is present in both sets, but it only appears once in the updated set1 because sets don’t allow duplicates.
Example 2: We can also pass a list (or any iterable) to update() to add its elements to the set.
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Explanation: update() method is called on d1 with the iterable [('c', 3), ('d', 4)], which adds the key-value pairs 'c': 3 and 'd': 4 to d1.
Example 3: You can update a set with multiple iterables in a single operation.
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Explanation: update() adds the key-value pairs 'c': 3 and 'd': 4 to d1, creating new keys with the specified values.
Example 4: update() method can also be used to add individual characters from a string to the set.
{1, 2, 3, 'e', 'l', 'h', 'o'}
Explanation: Each character in the string "hello" is treated as a unique element and added to the set. Duplicates (like 'l') are ignored.