Python Set add() Method (with Examples)

Python Set add() Method: In this tutorial, we will learn about the add() method of the set class with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 14, 2023

Python Set add() Method

The add() is an inbuilt method of the set class that is used to add an element to the set, the method accepts an element and adds the elements to this set. If the specified element already exists in the set, the method will not add the element to the set.

Syntax

The following is the syntax of add() method:

set_name.add(element)

Parameter(s):

The following are the parameter(s):

  • element – It represents the element to add in the set.

Return Value

  • None - It does not return any value.

Example 1: Use of Set add() Method

# 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'}

Example 2: Use of Set add() Method

Demonstrating example for adding an element that exists in the set.

# 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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.