set add() in python
In Python, a set is an unordered collection of unique elements. The add()
method is used to add an element to a set.
Syntax:
set.add(element)
Here, set
is the set to which the element is to be added, and element
is the element to be added to the set.
Example:
# create a set
fruits = {"apple", "banana", "cherry"}
# add an element to the set
fruits.add("orange")
# print the updated set
print(fruits)
Output:
{'banana', 'orange', 'cherry', 'apple'}
In the above example, we first create a set fruits
containing three elements. Then, we use the add()
method to add the element "orange"
to the set. Finally, we print the updated set which now contains four elements.
Note: If the element to be added is already present in the set, the add()
method does not add it again. The set remains unchanged.