zjm1126
zjm1126

Reputation: 66637

Why am I getting an error using 'set' in Python?

s = set('ABC')
s.add('z')
s.update('BCD')
s.remove('DEF') # error here
s -= set('DEFG')

Upvotes: 7

Views: 12753

Answers (4)

Rafał Dowgird
Rafał Dowgird

Reputation: 45071

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

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

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881555

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!

Upvotes: 18

EMiller
EMiller

Reputation: 1148

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

Upvotes: 0

gimel
gimel

Reputation: 86354

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

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

Upvotes: 2

Related Questions