1. remove() method in Python Sets
The remove() method in Python Sets can be used to remove an element in the given set. This method performs the modification on existing set and returns ‘None’.
Syntax
set.remove(element)
Let’s try to remove the existing element in a given set,
s = {'one', 2, 3, 'two', 'four'}
print('Before removal : ', s)
s.remove('two') # removing two from set
print('After removal : ', s)
O/P
Before removal : {2, 3, ‘four’, ‘two’, ‘one’}
After removal : {2, 3, ‘four’, ‘one’}
Please note that, if we try to remove an element that does not exists in set, then, we will get KeyError.
2. discard() method in Python Sets
The discard() method in Python Sets is same as remove() method and is used to remove an element in the given set. This method performs the modification on existing set and returns ‘None’.
Syntax
set.discard(element)
Let’s try to remove the existing element in a given set,
s = {'one', 2, 3, 'two', 'four'}
print('Before removal : ', s)
s.discard('two') # removing two from set
print('After removal : ', s)
O/P
Before removal : {2, 3, ‘four’, ‘two’, ‘one’}
After removal : {2, 3, ‘four’, ‘one’}
Only difference is that, if we try to remove an element that does not exists in set, then, discard() method does not raise any error rather the set remains unaffected.
c
3. clear() method in Python Sets
The clear() method in Python Sets is used to delete all elements in the given set and makes it empty. This method performs the modification on existing set and returns ‘None’.
Syntax
set.clear()
Let’s try to remove the existing element in a given set,
s = {'one', 2, 3, 'two', 'four'}
print('Before removal : ', s)
s.clear() # empties set
print('After removal : ', s)
O/P
Before removal : {2, 3, ‘four’, ‘two’, ‘one’}
After removal : set()
c
4. Using del statement in Python Sets
The del() statement in Python Sets deletes the set completely.
Syntax
del set
Let’s try to remove the existing element in a given set,
s = {'one', 2, 3, 'two', 'four'}
print('Before removal : ', s)
del s # deallocates the memory occupied by set s
print('After removal : ', s)
O/P
Before removal : {2, 3, ‘one’, ‘two’, ‘four’}
Traceback (most recent call last):
File “”, line 4, in
NameError: name ‘s’ is not defined
Please note that, adding an element in Set is an optimized process, with time complexity a O(1).
c
