Open In App

Set add() Method in Python

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The set.add() method in Python adds a new element to a set while ensuring uniqueness. It prevents duplicates automatically and only allows immutable types like numbers, strings, or tuples. If the element already exists, the set remains unchanged, while mutable types like lists or dictionaries cannot be added due to their unhashable nature. Example:

Python
a = set()
a.add('s')
print(a)

# adding 'e' again
a.add('e')
print(a)

# adding 's' again
a.add('s')
print(a)

Output
{'s'}
{'s', 'e'}
{'s', 'e'}

Explanation: This code initializes an empty set a, then adds ‘s’ and ‘e’ using the add() method. Since sets store only unique values, adding ‘s’ again has no effect, ensuring each element appears only once.

Set add() Syntax

set.add( elem )

Parameter: elem is the element to be added to the set.

Returns: It does not return anything (None).

Set add() Method Examples

Example 1: In this example, we have a set of characters and we use the add() method to insert a new element. Since sets only store unique values, adding the same element multiple times has no effect.

Python
a = {'g', 'e', 'k'}

# adding 's'
a.add('s')
print(a)

# adding 's' again
a.add('s')
print(a)

Output
{'g', 's', 'e', 'k'}
{'g', 's', 'e', 'k'}

Explanation: This code initializes a set a with elements ‘g’, ‘e’, and ‘k’, then adds ‘s’ using the add() method. Since sets store only unique values, adding ‘s’ again has no effect, ensuring each element appears only once.

Example 2: In this example, we have a set of numbers and we use the add() method to insert a new element. Since sets only store unique values, adding the same element multiple times has no effect.

Python
a = {6, 0, 4}

# adding 1
a.add(1)
print(a)

# adding 0
a.add(0)
print(a)

Output
{0, 1, 4, 6}
{0, 1, 4, 6}

Explanation: This code initializes a set a with elements 6, 0 and 4, then adds 1 using the add() method. Since sets store only unique values, adding 0 again has no effect, ensuring each element appears only once.

Example 3: In this example, we have a set of characters and use the add() method to insert a tuple, while the update() method is used to add elements from a list. Since sets only store unique values, duplicates are ignored.

Python
s = {'g', 'e', 'e', 'k', 's'}
t = ('f', 'o')
l = ['a', 'e']

# adding tuple t to set s.
s.add(t)

# adding list l to set s.
s.update(l)
print(s)

Output
{'a', 'g', 'e', 'k', 's', ('f', 'o')}

Explanation: The code initializes a set s, automatically removing duplicate ‘e’. It adds the tuple t ((‘f’, ‘o’)) using add(), as tuples are hashable, and inserts elements from list l ([‘a’, ‘e’]) using update(). Since sets store unique values, duplicate ‘e’ is ignored.

Read More on Set Methods



Next Article
Article Tags :
Practice Tags :

Similar Reads