Python Set Add():

The add() method adds a new element to the existing set in python. However, if the same value is already present in the set, the add() method doesn’t add the element.

Method signature

The signature for the add() method is as shown below. Here, s1 is a set, where element e is to be added.

s1.add(e)

Method parameters and return type

  • The add() method takes exactly one parameter of primitive type.
  • However, it doesn’t return any value

Python Set Add Examples:

Example 1: In this example, let us take a set1 with a set of numbers. Here, We will add a number that was not present in the existing set.

#Initializing the Set
set1 = {79,99,93,46,60}

# Adding new element to the set.
set1.add(45)
#Printing the set after adding
print("Set 1 ",set1)

Output

Set 1  {99, 45, 46, 79, 60, 93}

Example 2: In this example, let us take a mixed set that has the name, score, branch and experience of a student. In the meantime, If we want to add the student’s location as well. We do it with add() method.

Firstly, we will add element “Mumbai” in the set stud1. Thereafter, When we add element “mumbai” to the same set stud1, surprisingly, this also gets added, just because python is case sensitive and “mumbai” is different from “Mumbai”.

#Intializing the Set
stud1={"Ram",69.5,"Computer","3 yrs"}
# Adding new element to the set.
stud1.add("Mumbai")
# Adding same element but in Small case letters
stud1.add("mumbai")
#Printing the set after adding
print("Stud 1 ",stud1)

Output

Stud 1  {'Mumbai', 69.5, '3 yrs', 'Ram', 'mumbai', 'Computer'}

Example 3: In this example, let us demonstrate the add() method to show how it works when we try to add element that was already present in the set.

#Intializing the Set
s1 = {"python",5,11.25}
# Adding new element 
s1.add(11.25)
# Printing the Set
print("Set s1 ",s1)

Output

Set s1  {11.25, 'python', 5}

Conclusion

The add() method checks for the presence of new element in the existing set. Thereafter, It adds the element to the existing set only if that element is not present in the list.

References

Happy Learning 🙂

Leave A Comment