7
s = set('ABC')
s.add('z')
s.update('BCD')
s.remove('DEF') # error here
s -= set('DEFG')
5
  • 1
    @zjm1126: please include traceback next time. Commented Jan 3, 2010 at 6:29
  • i'm sorry,what is the 'traceback '??? Commented Jan 3, 2010 at 8:16
  • >>> s.remove('DEF') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'DEF' Commented Jan 3, 2010 at 8:22
  • @zjm1126: Traceback is the actual error message you actually get when you actually run this in Python. It shows the lines of code and "traces the error back" from the thing that failed to the thing that initiated execution. @Adam Bernier: It helps to update the question rather than add more hard-to-read comments. You may not have enough reputation. In which case, it may be better to wait for the author to learn how to do it. Commented Jan 3, 2010 at 12:39
  • @S.Lott: point well taken. My rationale for the hard-to-read comment is the OP's difficulties with English. Commented Jan 4, 2010 at 1:34

4 Answers 4

18

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Just curious Why python chooses KeyError to raise other than any other error?
@dlmeetei set always stores data as unique keys and when we perform operations, it searches using those keys. So, if a key is not found it'll throw KeyError.
2

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

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

Comments

0

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

0

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

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

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.