Tim
Tim

Reputation: 1471

Python set operation remove(index)

I am using the below program in python 3.4.3 (.py) script

number = {1,2,1,4,5,6,9}
print(number)
number.add(-5)  # adding some random number to the set
number.remove(3) # in this line python reports KeyError
print(number)
number.pop()
print(number)

but when i use other index

number.remove(2)  # works fine
number.remove(5)  # works fine 

is there any specific reason why i couldn't use the index 3 to be removed.

Upvotes: 1

Views: 1074

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22420

Have a look at the documentation for remove(elem):

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

Therefore, the reason number.remove(2), number.remove(5) works and number.remove(3) does not is because both 2 and 5 are present in number while 3 is not.


Note if you do not want to raise a KeyError you can use discard(elem):

Remove element elem from the set if it is present.

It also removes an element from a set but does not raise a KeyError, if elem does not exist.

Upvotes: 1

iacob
iacob

Reputation: 24261

remove(x) doesn't remove the item indexed x from the set (sets are unordered in Python), but the element with value x:

remove(elem) Remove element elem from the set. Raises KeyError if elem is not contained in the set.

Upvotes: 1

Related Questions