Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python Set add() method



The Python Set add() method is used to add a single element to a set. If the element is already present in the set the set remains unchanged because sets do not allow duplicate elements. The add() method modifies the set in place and does not return any value. The adding of the element will be happen if the element is unique in the set.

Syntax

Following is the syntax and parameters of Python Set add() method −

set.add(element)

Parameter

This method accepts the following parameter −

element: The element to be added to the set. This can be any hashable type such as numbers, strings or tuples.

Return value

This method does not return a value.

Example 1

Following is the basic example of the Python Set add() method. Here we are creating a set with 3 elements and adding a fourth element to it.

# Define a set
my_set = {1, 2, 3}

# Add an element to the set
my_set.add(4)

# Print the updated set
print(my_set)

Output

{1, 2, 3, 4}

Example 2

Since sets in Python doesn't allow duplicate elements if we try to add an existing element using this method the contents of the set remain unchanged. In the example below we are trying to add an existing element (3) to the set.

# Define a set
my_set = {1, 2, 3}

# Add a duplicate element to the set
my_set.add(3)

# Print the updated set
print(my_set) 

Output

{1, 2, 3}

Example 3

We also add different types of data to a set. In here, we are creating an empty set and adding an integer, string and a tuple to it, using the add() method −

# Define an empty set
my_set = set()

# Add elements of different types to the set
my_set.add(1)
my_set.add("Hello")
my_set.add((1, 2, 3))

# Print the updated set
print(my_set)  

Output

{1, (1, 2, 3), 'Hello'}

Example 4

Now, lets try to add multiple elements to a set using a loop.

# Define an empty set
my_set = set()

# Add elements to the set in a loop
for i in range(5):
    my_set.add(i)

# Print the updated set
print(my_set)  

Output

{0, 1, 2, 3, 4}
python_set_methods.htm
Advertisements