The set
data type represents a collection of unordered, unique elements.
Sets are mutable meaning that they can be modified by adding, removing, or replacing elements.
The add()
method is used to add a single element to a set
.
myset.add(e)
e |
The element to be added to the set. |
The add()
methods adds element e
to the set. There will be no effect if the element is already present.
myset = {'Python', 'Java', 'C++'}
#add elements to the set
myset.add('PHP')
myset.add('HTML')
myset.add('Javascript')
print(myset)
add() vs update()
If we want to add multiple elements to a set, we may use the add() method with a for loop as follows.
myset = {'Python', 'Java', 'C++'}
elements = ['PHP', 'HTML', 'Javascript']
#add the elements to the set
for e in elements:
myset.add(e)
print(myset)
However, the set
class also contains the update()
methods which allows you to add multiple elements to a set simultaneously. This approach is more convenient than adding each element individually via a loop.
myset = {'Python', 'Java', 'C++'}
elements = ['PHP', 'HTML', 'Javascript']
#use update() to add elements to the set
myset.update(elements)
print(myset)