Sometimes you want to remove something collection if it’s in there.
set → discard()
dict → pop()
list → requires checking first on try / except.
deque → requires checking first on try / except.
It’s a weird inconsistency and I’m not aware of any reason beyond tradtion.
discard would be consistent with set and list and deque already have pop methods.
This works, but it’s both less readable and slower (assuming .remove, .pop, .append and .__contains__each take some time C).
It’s complexed than it needs to be. Another thing this lacks are standards. .append, .remove are not guaranteed for, say a Sequence[...]). Just adding a simple .discard to all sequences would be easier.
I think it’s actually stranger that the indexed sequence types support .remove() at all .
The dict and set types are “content-addressable”. Insertion and deletion work by object value, are O(1), and can’t be indexed directly by ordinals.
The indexed sequence types share none of those properties.
It became “a tradition” because nobody cared enough about sequence.discard(unwanted) to press for it in the early years. Lack of compelling use cases. Things like dict.pop(unwanted)were driven by frequently expressed need. dict.pop() in fact was added in Python 2.0, along with dict.popitem(). They didn’t exist from the start.
I’m neutral on whether sequence.discard() is added now. Not an itch I have, but if enough others do, fine by me.
sequence.remove can be more efficient than set.remove/dict.pop when the size of a typical sequence for the specific use case is expected to be small, since sets and dicts require hashing first.
Use cases for sequence.discard are not uncommon at all, including:
So while yes it is easily worked around with a try-except block, it would still be a meaningful method to have.
For those curious, list.discard() can be implemented by removing a single line (i.e. raise ValueError) from the list.remove() implementation. Here is a patch.
I suspect that some of the ‘remove’ examples could now use a set rather than a list, but predate that addition, or wrap OS functions that return (short) lists.
Rather than a new, near duplicate function, I would prefer a proposal to add a parameter to the existing list.remove to raise or not upon value absence (defaulting to True for back compatibility).
Rather than a new, near duplicate function, I would prefer a proposal to add a parameter to the existing list.remove to raise or not upon value absence (defaulting to True for back compatibility).
I think this would be inconsistent with the other API’s as mentioned in the original post. As for the implementation, that could be moved to a helper to deduplicate.
Anyhow, if anyone wants to propose this as a PEP, (I myself would find it useful, though not particularly important) I am happy to help write it/co-author.