Add list.discard(x), which removes the first item equal to x if one is present and does nothing otherwise, returning whether an item was removed. It is the non-raising counterpart to list.remove(), as set.discard() is to set.remove().
The symmetry with sets is incomplete, because lists can have multiple copies of the same item, and it’s not at all clear whether discard should remove just one or all of the copies.
I would expect list.discard(x) to do the same thing as list.remove(x) when the list has multiple copies of x. That is, I would expect the only difference between discard and remove would be in suppressing the exception when the element was not present.
With a sufficiently degenerate object, a set can have multiple things that match a remove/discard operation, and in that case, just one of them will be removed. It stands to reason that a list should do the same.
TBH, I don’t see the number of values as a problem. x.discard() is a non-erroring version of x.remove(). list.remove removes the first instance, so list.discard would do the same thing.
I do think @sciolist’s point about what natural operations are on a class, and what named methods imply about intended use patterns, is a bit stronger:
I pretty much never use remove(), and instead usually use iterators or comprehensions if I need to filter values, which deal with the list as a sequence instead of a bag of objects. If a bag of objects is needed, I would tend to use a different structure.
My bigger concern is that this is about mirroring a small aspect of the set API without much consideration of what the list API now will be. It will now have a non-erroring version of remove(), but not of index(), which will feel to me like a bigger asymmetry than the current asymmetry between set.remove and list.remove.
It would also be strange to make list.discard return bool without also making set.discard return bool, if the whole idea is to mimic the API. Being able to say if x.discard(y) does seem to be useful in both cases.
Anyway, no strong opinion +/- on this. I don’t think these minor inconsistencies should be blocking, just considered.
No strong opinion from me either, but I’m not totally convinced by the rationale for a new method over a keyword argument; if I were using list.remove and was annoyed by it raising an exception, I think the natural thing to do is check the signature for a missing_ok flag, not try to use a set method on a list.
An analogy can be made to string search/replace. Like str.replace() and re.sub(), an optional count parameter could be added to make it easy to discard just the first matching item or all of them. (The same goes for list.remove().)
Otherwise I predict people will implement discard-all as:
I don’t think this would be a positive improvement. lists aren’t sets, and they don’t need to have the same interface, nor do they really benefit from some notion of being interchangable structures, they serve different purposes.
adding a keyword-arg to .remove not to raise seems fine here (as was already suggested above).
Keyword args are horrible for forward/backward compatibility, because you can’t detect them or easily handle when they’re absent (no way to be sure the TypeError is due to the argument).
An importable function that does .discard() when available or try: ....remove() when not (and possibly handling some del x[x.index(v)] variants) is the most compatible option. It’s easy to detect if an import fails, and to provide your own alternative.
from some_mod import discard
discard(a_list)
discard(a_set)
A duck-typed method is another very good way to handle compatibility, provided the method name is relatively consistent (i.e. .discard() on list does the same kind of thing as on set rather than being totally different - bear in mind that the intent is to remove a particular value without failing if it’s absent, so if that’s what discard() does, then it meets it. The intent doesn’t depend on the particular type).
But in a future where list and set are interchangeable for most operations and the difference is just order and cardinality preservation, being able to just use .discard is clearly the best.
Steve, I get where you’re coming from, but I really, really disagree with the idea that we should aim for a future where sets and lists are interchangeable. If that’s the goal here (which I don’t think it is – I think people just wanted a convenience function, and set just happened to have a name for precedent), my ±0 turns into a vehement -1. They are fundamentally different datastructures, and I think the conflation of them would be very bad in the long term.
More practically, the forwards compatibility argument doesn’t really work here. If you want to support older Python versions, you’ll just do if x in list: list.remove(x) or the try/except dance (i.e., what all Python code currently does). Regardless of whether it’s a keyword argument or a method, nobody is going to add compatibility checks.
list.add makes more sense in that case. The addfunction adds the element somewhere in the collection (but we don’t know where). The appendspecifically adds an element to the end.
This is how clojure was designed. conj adds somewhere to any collection type, whereas cons always prepends. The conj method works on sets, lists and vectors, whereas cons only works on lists and vectors.
Honestly, I’m quite neutral on this. Introducing add() as an alias for append() in MutableSequence would be more interesting, as would adding other Set operators to Mapping.
It should be noted that the symmetry between MutableSequence, MutableSet, and MutableMapping is already broken by pop(), which takes on different meanings and has different signatures depending on the data type in question.
Side note: I have occasionally needed a generic method to iterate over both Sequence and Mapping types, which forced me to create ad-hoc utility functions. I have often felt the need for keys, values, and items methods for Sequence types as well, but I suppose keys and items have no sense for a sequence.
Both are common. A search of the 5,000 most downloaded PyPI projects [1] finds 1,062 matches for the first form across 411 projects and 331 for the second across 164 projects.
Could you post a link to a Gist with the results? It would help me understand how the two patterns were used. I support the change, but I’d like to see which projects may benefit.
I am (or was) preferring a new keyword argument like missing_ok=False to be added to existing list.remove, beacuse I do not consider suppressing ValueError significant enough to justify a new method.
But I also consider returning the status of the removal [e.g. bool: removed or not found or int: index or -1] an essential feature. list.remove returns None if it returns. While it would be still backward compatible if it were returning other type when used with a kwarg not existing before, I feel that would be not nice. The new feature would not add a sentence or two to the docs, but it would split it into two sections.
That’s why I now prefer the discard() over missing_ok=...
I agree that a built-in way to remove all occurrence would be good. I believe adding parameter all=False instead of using count would be better, though. The problem with count is that if the default is to remove one, removing all would require using something like count=-1 which isn’t explicit at all.
If all=False would be added, it would be logical if the method returned the number of removed items instead of a Boolean.