Python set Method - add()
The add()
method in Python is used to add an element to a set. The method modifies the original set in place and does not return anything. If the element already exists in the set, the add()
method has no effect.
The syntax for the add()
method is as follows:
set.add(elem)
Here, set
refers to the set to which the element needs to be added, and elem
is the element to be added.
Example:
# Creating a set my_set = {1, 2, 3} # Adding an element to the set my_set.add(4) # Displaying the modified set print(my_set) # Output: {1, 2, 3, 4} # Adding an existing element to the set my_set.add(2) # Displaying the modified set print(my_set) # Output: {1, 2, 3, 4}
In the above example, the add()
method is first used to add the integer 4
to the set my_set
. The original set is modified and the output shows the updated set. Then, the add()
method is used again to add the integer 2
to the set, but since 2
already exists in the set, the add()
method has no effect. The modified set is printed again to show that it remains the same. It is important to note that sets are unordered, so the order of elements in the set may not match the order in which they were added.