Python - Set add() Method


Advertisements

The Python set 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.

Example: Add new element

In the below example, 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)

Output

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

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)

Output

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

Sets Methods




Advertisements