tags:

views:

113

answers:

4
s = set('ABC')
s.add('z')
s.update('BCD')
s.remove('DEF') # error here
s -= set('DEFG')
+2  A: 

The argument to set.remove() must be a set member.

'DEF' is not a member of your set. 'D' is.

gimel
A: 

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

EMiller
+5  A: 

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!

Alex Martelli
A: 

Do you expect 'DEF' to be treated as an element or a set?

In the latter case use s.difference_update('DEF').

Rafał Dowgird
It does not matter how he wants them to be treated, the problem is that 'EF' do not exist in the set, hence the error message.
Helen Neely
Disagreed. "You are calling the wrong method for this argument" is also a valid answer to the question. Given that the author is using strings as sets, it is valid to suspect that he needs `difference_update()` here.
Rafał Dowgird