Python Set add()

Python Set add(element) method adds the element to the set.

In this tutorial, we will learn the syntax of set.add() method and go through examples covering different scenarios for the arguments that we pass to add() method.

Syntax

The syntax of set.add() is

</>
Copy
set.add(element)

where

ParameterDescription
elementElement to add to the set.

Examples

1. Add element to set

In the following program, we will add the element e to the set s.

Python Program

</>
Copy
s = {'apple', 'banana', 'cherry'}
e = 'mango'
s.add(e)
print(s)

Program Output

{'banana', 'apple', 'cherry', 'mango'}

2. Add element to set, but element is already present

In the following program, we will add the element e to the set s. The catch is that the element e is already present in the set s.

Python Program

</>
Copy
s = {'apple', 'banana', 'cherry'}
e = 'banana'
s.add(e)
print(s)

Program Output

{'cherry', 'banana', 'apple'}

If the element is already present in the set, then the set remains unchanged after add() method execution.

Conclusion

In this Python Tutorial, we learned about Python set method set.add(). We have gone through the syntax of add() method, and its usage with example programs.