
Remove or delete an element from a set in Python
In Python, elements in a set can be removed by remove()
.
s = {'a', 'b', 'c'}
s.remove('a')
print(s) # {'b', 'c'}
remove()
returns None.
s = {'a', 'b', 'c'}
t = s.remove('a')
print(s) # {'b', 'c'}
print(t) # None
remove() takes one argument
s = {'a', 'b', 'c'}
s.remove('a', 'b')
# TypeError: remove() takes exactly one argument (2 given)
remove()
can remove only one element.
A set can't be an argument of remove()
s = {'a', 'b', 'c'}
s.remove({'a', 'b'})
# KeyError: {'a', 'b'}
remove() can't remove a value that doesn't exist
s = {'a', 'b', 'c'}
s.remove('d')
# KeyError: 'd'
If trying to remove a value that isn't in a set, Python raises the KeyError exception. So you may want to check the existence before removing like this.
s = {'a', 'b', 'c'}
if 'a' in s:
s.remove('a')
print(s) # {'c', 'b'}
You may be happy to use discard()
s = {'a', 'b', 'c'}
s.discard('a')
print(s) # {'b', 'c'}
discard()
removes an element from a set like remove()
and the difference of those is discard()
doesn't raise the exception if the value doesn't exist.
s = {'a', 'b', 'c'}
s.discard('d')
print(s) # {'b', 'a', 'c'}
Comments
Powered by Markdown