1

Is there a deleting method for deleting an element of a set that takes a parameter to return if there is no element to delete that matches the parameter you gave it to delete?

So it would be something like set.discard(a,b) where a is the parameter that you want to delete and b is the parameter that gets returned if a is not found.

patthoyts
  • 32,320
  • 3
  • 62
  • 93
mikeLundquist
  • 769
  • 1
  • 12
  • 26
  • 2
    What should it return if it was found and removed? – poke Jun 13 '15 at 12:47
  • 1
    The answer is a reassuring; no :) See: [``set()``](https://docs.python.org/2/library/stdtypes.html#set) – James Mills Jun 13 '15 at 12:49
  • 1
    Python's set methods do not even return the removed element _if_ it was in the set; otherwise you could do `set.discard(a) or b`. But as it stands, you'll have to implement that method yourself. – tobias_k Jun 13 '15 at 12:50
  • If the item was successfully deleted nothing should be returned. – mikeLundquist Jun 13 '15 at 13:45

2 Answers2

2

Something like this?

def _discard(s, key, ret):
    try:
        s.remove(key)
    except KeyError:
        return ret
    return key    

s = set([1,2,3])
ret = "not found"

key = 4

print _discard(s, key, ret), s

key = 3

print _discard(s, key, ret), s
boardrider
  • 5,882
  • 7
  • 49
  • 86
  • A better name is `pop(container, item, default=None)` – jfs Jun 13 '15 at 13:33
  • I agree, @J.F.Sebastian: @user4757074 can even implement it as a method of a subclass of `set` (http://stackoverflow.com/questions/798442/what-is-the-correct-or-best-way-to-subclass-the-python-set-class-adding-a-new). – boardrider Jun 13 '15 at 14:44
  • btw, `set.pop` exists already but it has a strange behavior. I would use `dict.pop` as an example instead. – jfs Jun 13 '15 at 14:48
1

Not built-in. remove(elem)

remove(elem)

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

Try to catch the exception in your own function maybe? When exception caught return your element b.

Ely
  • 10,860
  • 4
  • 43
  • 64