0

My example is pretty simple, but still: a have a set called basket with n elements (we enter n and then the elements). And what I want is to remove all elements with 'apple' in them. However there can be cases where there is no 'apple' in the set at all and that's when it bugs. When there is 'apple' it's ok.

n = int(input("n= "))
basket = set()
print(f"{n} elements: ")
for i in range(n):
    e = input(f"element {i+1}: ")
    basket.add(e)
print(basket)
basket.remove('apple')
print(basket)

I expected to be ok even when there is no 'apple' in the set, but it gives error.

  • If you want to remove an element without caring whether or not it actually exists already, use `.discard()` instead of `.remove()`. – jasonharper Jul 19 '23 at 16:37

1 Answers1

0

Use set.discard instead of set.remove.

From the docs:

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

remove raise a KeyError if the element is not present. discard does not.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
  • @SimonaDavarska Glad it was helpful. But see also [Thanks in a comment?](https://meta.stackoverflow.com/q/267490/11082165) – Brian61354270 Jul 19 '23 at 16:40