Python Set – add()

Python Set – add() method

Python Set add() method is used to add an element to the set.

add() methods returns None. It modifies the set on which you are calling the add() method.

In this tutorial, we will learn the usage of add() method of Set class, using different scenarios.

Example 1: Add an element to set

In this example, we shall add an element to the set. The element we are adding, is not already present in the set.

Python Program

#initialize set
set_1 = {'a', 'b', 'c'}

#add() method
set_1.add('g')

print(set_1)
Run

Output

{'g', 'c', 'a', 'b'}

Example 2: Add an duplicate element to set

In this example, we shall pass a duplicate element, element that is already present in the set, to add() method. The resulting set should be unchanged.

Python Program

#initialize set
set_1 = {'a', 'b', 'c'}

#add() method with duplicate element
set_1.add('c')

print(set_1)
Run

Output

{'c', 'a', 'b'}

The resulting set is unchanged. The elements of the original set and modified set are same.

Summary

In this tutorial of Python Examples, we learned how to use add() method to add elements to a set, with the help of well detailed Python programs.