The add() function in python helps to insert specified elements into the set. This method does not allow to the addition of duplicate elements.
set.add(element) #where element which is to be add
The add() function takes a single parameter. This function doesn't add the element if the specified element already exists in the set.
Parameter | Description | Required / Optional |
---|---|---|
element | the element that is added to the set | Required |
The add() method doesn't return any value, it just updates the set by adding a particular element. We can add tuples also using this add() method. Like elements, the same tuples can't be added again.
# alphabet set
alphabet = {'a', 'b', 'd', 'e', 'f'}
# adding 'c'
alphabet.add('c')
print('Alphabets are:', alphabet)
# adding 'b' again
alphabet.add('b')
print('Alphabets:', alphabet)
Output:
Alphabets are:{'a', 'b', 'd', 'e', 'c', 'f'} Alphabets are:{'a', 'b', 'd', 'e', 'c', 'f'} # The order may be different
# alphabet set
alphabet = {'a', 'b', 'c'}
# a tuple ('d', 'e')
tuple = ('d', 'e')
# adding tuple
alphabet.add(tuple)
print('Alphabets are:', alphabet)
# adding same tuple again
alphabet.add(tuple)
print('Alphabets are:', alphabet)
Output:
Alphabets are: {('d', 'e'), 'c', 'b', 'a'} Alphabets are: {('d', 'e'), 'c', 'b', 'a'}