How does the add() method work in Python sets?

How does the add() method work in Python sets?

a) Adds an element to the set
b) Removes an element from the set
c) Returns the size of the set
d) Merges two sets

Answer:

a) Adds an element to the set

Explanation:

The add() method in Python sets is used to add a new element to the set. If the element is already present in the set, the set remains unchanged, as sets do not allow duplicate elements.

# Example of add() method
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)  # Output: {'apple', 'banana', 'cherry'}

In this example, the add() method adds “cherry” to the fruits set. Since “cherry” was not previously in the set, it is added as a new element.

The add() method is a simple and efficient way to add elements to a set while ensuring that all elements remain unique.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top