Python Tutorial Python Advanced Python References Python Libraries

Python Set - add() Method



The Python add() method is used to add a new element to the set. As a set does not allow duplicate elements, hence an already present element will not be added again in the set.

Syntax

set.add(elem)

Parameters

elem Required. specify the element which need to be added in the set.

Return Value

None.

Example: Add new element

In the example below, the add() method is used to add a new element in the set called MySet.

MySet = {'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'}
#Adding 'SUN' to the set
MySet.add('SUN')   
print(MySet)

The output of the above code will be:

{'SUN', 'WED', 'FRI', 'MON', 'THU', 'SAT', 'TUE'}

Example: Add already present element

Duplication of elements in a set is not allowed. Hence, it checks whether the element which is being added is present in the set or not.

week = {'MON', 'TUE', 'WED'}
#Add 'MON' to the set
week.add('MON')   
print(week)

The output of the above code will be:

{'MON', 'TUE', 'WED'}

❮ Python Set Methods