Home »
Python
Python Set add() Method with Example
Python Set add() Method: Here, we are going to learn how to add an element to the set using add() method in Python?
Submitted by IncludeHelp, on November 27, 2019
Set add() Method
add() method is used to add an element to the set, the method accepts an element and adds the elements to this set.
Note: If the specified element already exists in the set, the method will not add the element to the set.
Syntax:
set_name.add(element)
Parameter(s):
- element – It represents the element to add in the set.
Return value:
It does not return any value.
Example 1:
# declaring a set
cities = {"New Delhi", "Mumbai"}
# printing set before adding the element
print("cities = ", cities)
# adding new city i.e. new element
cities.add("Banglore")
cities.add("Gwalior")
# printing set after adding the elements
print("cities = ", cities)
Output
cities = {'New Delhi', 'Mumbai'}
cities = {'New Delhi', 'Mumbai', 'Banglore', 'Gwalior'}
Demonstrating example (adding an element that exists in the set)
Example 2:
# declaring a set
cities = {"New Delhi", "Mumbai"}
# printing set before adding the element
print("cities = ", cities)
# adding new city i.e. new element
cities.add("Banglore")
cities.add("Gwalior")
# printing set after adding the elements
print("cities = ", cities)
# adding "Gwalior" element again
cities.add("Gwalior")
# printing set after adding the elements
print("cities = ", cities)
Output
cities = {'Mumbai', 'New Delhi'}
cities = {'Gwalior', 'Mumbai', 'New Delhi', 'Banglore'}
cities = {'Gwalior', 'Mumbai', 'New Delhi', 'Banglore'}
See the output, we have added element "Gwalior" and tried to add it again, but the second time element "Gwalior" is not added.
ADVERTISEMENT
ADVERTISEMENT