Python Set add()

The add() method adds a given element to a set. If the element is already present, it doesn't add any element.

Example

prime_numbers = {2, 3, 5, 7}

# add 11 to prime_numbers prime_numbers.add(11)
print(prime_numbers) # Output: {2, 3, 5, 7, 11}

Syntax of Set add()

The syntax of add() method is:

set.add(elem)

add() method doesn't add an element to the set if it's already present in it.

Also, you don't get back a set if you use add() method when creating a set object.

noneValue = set().add(elem)

The above statement doesn't return a reference to the set but 'None', because the statement returns the return type of add which is None.


Set add() Parameters

add() method takes a single parameter:

  • elem - the element that is added to the set

Return Value from Set add()

add() method doesn't return any value and returns None.


Example 1: Add an element to a set

# set of vowels
vowels = {'a', 'e', 'i', 'u'}

# adding 'o'
vowels.add('o')
print('Vowels are:', vowels) # adding 'a' again
vowels.add('a')
print('Vowels are:', vowels)

Output

Vowels are: {'a', 'i', 'o', 'u', 'e'}
Vowels are: {'a', 'i', 'o', 'u', 'e'}

Note: Order of the vowels can be different.


Example 2: Add tuple to a set

# set of vowels
vowels = {'a', 'e', 'u'}

# a tuple ('i', 'o')
tup = ('i', 'o')

# adding tuple
vowels.add(tup)
print('Vowels are:', vowels) # adding same tuple again
vowels.add(tup)
print('Vowels are:', vowels)

Output

Vowels are: {('i', 'o'), 'e', 'u', 'a'}
Vowels are: {('i', 'o'), 'e', 'u', 'a'}

You can also add tuples to a set. And like normal elements, you can add the same tuple only once.


Also Read:

Did you find this article helpful?