Python Set add() Method
The set.add()
method adds an element to the set. If an element is already exist in the set, then it does not add that element.
Syntax:
set.add(element)
Parameters:
element: (Required) The element that needs to be added to the set.
Return value:
No return value.
The following adds elements using the set.add()
method.
lang = {'Python', 'C++', 'Java', 'C'}
lang.add('Go')
lang.add('Dart')
print(lang)
{'Java', 'C++', 'Dart', 'Python', 'Go', 'C'}
Set is an unordered collection, so added elements can be in any order.
The add()
method can add a tuple object as an element in the set, as shown below.
lang_tuple = ('PHP', 'Go')
lang = {'Python', 'C++', 'Java', 'C'}
lang.add(lang_tuple)
print(lang)
{'C', ('PHP', 'Go'), 'Java', 'Python', 'C++'}
Note that you can add the same tuple only once as in the case of other elements. Lists and Dictionaries cannot be added to the set because they are unhashable.