Skip to content

Python Set add() Method

How to use Python's Set add() method to insert a single element into a set while handling duplicates and immutable data types like tuples.

The Set add() method adds a single element to a set. If the element is already present in the set, the set remains unchanged.

Syntax

my_set.add(element)

add() Parameters

Python Set add() method parameters:

Parameter Condition Description
element Required The element you want to add to the set.

add() Return Value

Python Set add() method does not return any value: it modifies the set in-place.

Examples

Example 1: Add an element to a Set

For example, let's add a string to a set:

my_set = {'Tom', 'David', 'Ryan'}
my_set.add('Anna')

print(my_set) # Output: {'David', 'Anna', 'Tom', 'Ryan'}

output

{'David', 'Anna', 'Tom', 'Ryan'}

Example 2: Add an element that already exists in a Set

If you try to add an item that already exists in the set, the method does nothing.

For example, let's add the string 'Anna' to my_set:

my_set = {'Tom', 'David', 'Anna'}
my_set.add('Anna')

print(my_set) # Output: {'Anna', 'Tom', 'David'}

output

{'Anna', 'Tom', 'David'}

Example 3: Add a Tuple to a Set

The item you want to add must be of immutable (unchangeable) type.

For example, you can add a Tuple to your set (since Tuples are immutable):

my_set = {'Tom', 'David', 'Anna'}
my_set.add((1, 2, 3))

print(my_set) # Output: {'David', 'Anna', (1, 2, 3), 'Tom'}

output

{'David', 'Anna', (1, 2, 3), 'Tom'}

Example 4: Add a List to a Set

Attempting to add a list directly to a set using add() will result in a TypeError. This is because lists are mutable and thus not hashable, which is a requirement for set elements!

my_set = {1, 2, 3}
my_set.add([4, 5]) # This will raise a TypeError because lists are not hashable

output

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    my_set.add([4, 5]) # This will raise a TypeError because lists are not hashable
TypeError: unhashable type: 'list'
Navigation