The add() method in Python Sets can be used to add an element in the given set.
Syntax
set.add(element)
Let’s try to add new element (string type) to the given set,
s = {'one', 2, 3, 'two', 'four'}
print('Before addition : ', s)
s.add('val') # adding val to given set s
print('After addition : ', s)
O/P
Before addition : {2, 3, ‘two’, ‘four’, ‘one’}
After addition : {2, 3, ‘two’, ‘four’, ‘val’, ‘one’}
Add Multiple Elements to a Set in Python
The update() method in Python Sets can be used to add multiple values to a given Python Set.
Syntax
set.update(object)
The object inside the update() method can be any iterable object (sets, tuples, lists, dictionaries etc).
Hence, with update() method, we can :
1. Add a set to a given set
2. Add a list to a given set
3. Add a tuple to a given set
4. Add a dictionary to a given set
s = {1, 2, 3, 4}
to_add = {'one', 'two', 'three', 'four'}
print('Before addition : ', s)
s.update(to_add) # adding set to_add in s
print('After addition : ', s)
O/P
Before addition : {1, 2, 3, 4}
After addition : {‘three’, 1, 2, 3, 4, ‘one’, ‘four’, ‘two’}
Please note that, adding an element in Set is an optimized process, with time complexity a O(1).
That’s all here.
