93
Python Set add() Method
Python add() method adds new element to the set. It takes a parameter, the element to add. It returns None to the caller. The method signature is given below.
Signature
Parameters
elem: element to be added.
Return
It returns None.
Let’s see some examples of add() method to understand it’s functionality.
Python Set add() Method Example 1
A simple example to add a new element in the set. It returns a modified set.
Output:
{1, 2, 3} After adding new element: {1, 2, 3, 4}
Python Set add() Method Example 2
Adding an element which already exist will not modifiy the set. Set does not store duplicate elements. See the example below.
Output:
{1, 2, 3} After adding new element: {1, 2, 3}
Python Set add() Method Example 3
Set also allows to store other datastructures like tuple, list etc. See the example below.
Output:
{1, 2, 3} After adding new element: {(4, 5), 1, 2, 3} After adding tuple: {1, 2, 3, (4, 5), (2, 3, 4)}
Next TopicPython Set