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.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.