s = set('ABC')
s.add('z')
s.update('BCD')
s.remove('DEF') # error here
s -= set('DEFG')
4 Answers
As others pointed out, 'DEF', the set member you're trying to remove, is not a member of the set, and remove, per the docs, is specified as "Raises KeyError if elem is not contained in the set.".
If you want "missing element" to mean a silent no=op instead, just use discard instead of remove: that's the crucial difference between the discard and remove methods of sets, and the very reason they both need to exist!
2 Comments
KeyError to raise other than any other error?KeyError.The argument to set.remove() must be a set member.
'DEF' is not a member of your set. 'D' is.
Comments
From http://docs.python.org/library/stdtypes.html :
remove(elem)
Remove element elem from the set. Raises KeyError if elem is not contained in the set.
'DEF' is not in the set
Comments
Do you expect 'DEF' to be treated as an element or a set?
In the latter case use s.difference_update('DEF').
2 Comments
difference_update() here.
Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'DEF'