add() of Sets in Python

add() of Sets in Python

The add() method is used with sets to insert a single element into the set. Sets are unordered collections of unique elements. The add() method adds the given element to the set. If the element is already present in a set then it does not add anything.

add function in Python

add() of Sets 

In Python, Sets have an add() method to insert a single element into the set. The add() method for sets ensures that the set remains unique, meaning it won’t allow duplicate elements. The add() method is particularly useful when you want to build a set dynamically by adding elements as you go. It provides a convenient way to maintain a collection of distinct values in your Python code.

Python Set add()

Syntax :

set1.add(element1)

add() method takes a single parameter.

Return Type :

add() method does not return any value. It returns None.

Run
#create set
#output : {1, 2, 3, 4, 5}
mySet = { 1, 2, 3, 4, 5 }
print(mySet)

#insert single element using add()
#"PrepInsta" will be added to the set
#output : {'PrepInsta', 1, 2, 3, 4, 5}
mySet.add("PrepInsta")
print(mySet)

#adding the element which is already present in the set
#output : {'PrepInsta', 1, 2, 3, 4, 5}
mySet.add(1)
print(mySet)
Output :

{1, 2, 3, 4, 5}

{'PrepInsta', 1, 2, 3, 4, 5}

{'PrepInsta', 1, 2, 3, 4, 5}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription