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.



Here, set is the set to which the element is to be added, and element is the element to be added to the set.


# create a set
fruits = {"apple", "banana", "cherry"}

# add an element to the set

# print the updated set


{'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.

About the author

William Pham is the Admin and primary author of With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.