📅  最后修改于: 2023-12-03 14:46:03.967000             🧑  作者: Mango
In Python, a Set is an unordered collection of unique elements. Python provides various methods to manipulate and perform operations on sets. One such method is update()
, which allows you to add multiple items to a set at once.
The update()
method modifies the original set by adding elements from another iterable object (such as another set, list, tuple, or string). It eliminates duplicate values and doesn't add elements that already exist in the set. The updated set contains all unique elements from both the original set and the iterable object.
The syntax for the update()
method is as follows:
set_name.update(iterable)
Here, set_name
is the name of the set that you want to update, and iterable
is an iterable object (e.g., set, list, tuple, or string) containing elements to be added.
Consider the following example to understand the usage of update()
:
fruits = {"apple", "banana", "cherry"}
more_fruits = ["mango", "banana", "grape"]
fruits.update(more_fruits)
print(fruits)
Output:
{'grape', 'cherry', 'banana', 'mango', 'apple'}
In the above example, we have an initial set fruits
containing three elements. We also have a more_fruits
list with three elements, one of which is already present in the fruits
set. When we use the update()
method on fruits
with more_fruits
, the set is modified, and the duplicate value "banana" is removed. The resulting set contains all unique elements from both sets.
The update()
method in Python sets is a convenient way to add multiple unique elements from an iterable object to an existing set. It eliminates duplicate values and modifies the set in-place. This method can be particularly useful when combining multiple sets or adding elements from lists, tuples, or strings into a set.