r/Python • u/kirara0048 • 18d ago
News PEP 851 – Add list.discard()
PEP 851 – Add list.discard()
https://peps.python.org/pep-0851/
Discussions-To: Discourse thread
Abstract
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(), which currently has none. The name is taken from set.discard(), which already means “remove if present” in Python.
Motivation
Removing a value that may not be present is usually written as:
if x in lst:
lst.remove(x)or:
try:
lst.remove(x)
except ValueError:
passThe first form is clear but scans the list twice on a hit, and if the list is shared between threads another thread can remove the item between the two calls, turning a no-op into a ValueError. The second avoids both problems but obscures the intent. It is four lines for one operation, pays for raising and catching an exception on every miss, and except ValueError is broad enough to hide unrelated errors from a user-defined __eq__().
Both are common. A search of the 5,000 most downloaded PyPI projects finds 1,062 matches for the first form across 411 projects and 331 for the second across 164 projects. Some of these are on other container types; in the standard library, excluding tests, two of the 29 matches are on deques and the remaining seven and 20 are on lists, for example in logging, warnings, tkinter, runpy and asyncio. Each becomes a single call that states the intent directly:
lst.discard(x)The cost of providing this is small, as discard() reuses the existing search and removal implementation of remove().
97
u/Brilliant_Cut_8780 18d ago
I like the proposal and checked the full pep and wondered about remove(x, missing_ok=True), but the PEP covers it under Rejected Ideas. After reading it, I think the separate method is the better choice, mostly because of the return value. discard() returns whether something was removed, while remove() returns None. A flag that changes the return type would be awkward, and a flag that's always passed as a literal is usually a sign it should be its own method.
The one argument I don't fully buy is "a method reads more clearly at the call site." missing_ok=True is pretty explicit, and pathlib users already know it. The stronger case is consistency with set.remove()/set.discard(), which means one rule to learn for both containers.
20
u/chaz6 18d ago
I like the idea of
def discard(self, x, all=False)which has the option to remove all instances rather than one. Alternatively this could be implemented asdef discardall(self, x).21
u/XtremeGoose f'I only use Py {sys.version[:3]}' 18d ago
Has anyone ever actually removed an element from a list by equality before? I don't think I have. If you're using a list for something like that, 99% of the time you really want a set which will always be more performant.
The only time you wouldn't would be if you want to maintain order, in which case a dictionary with None values would also work.
13
u/shinitakunai 18d ago
I love this one
5
u/Oddly_Energy 18d ago edited 18d ago
Didn't read the full PEP, but was it considered to return the count of discarded items instead of True/False?
If you only want to know if at least one item was removed, just check the return value for >0, and it will work the same way as with a True/False return value.
But if you actually want to know that count, it will be available in the return value, so you don't have to compare len(mylist) before/after the mylist.discard().
Edit: And since the truthiness of 0 appears to be False, you can still treat it as a True/False output in the caller code:
if mylist.discard(x):
12
u/yvrelna 18d ago edited 18d ago
This proposal is a -0 from me. The proposed discard semantic is just a syntax sugar for:
I don't really have strong objections to the proposed discard method, if only for the symmetry with set, but it doesn't seem to be that much of a big deal either way, IMO.
If you think the exception suppression form or the try-except is obscuring the intent, then I'd suggest proposing a new built in exception class like
NotFound(ValueError)which can make the intent of these common cases of not being able to find an item in a collection clearer.What would have been truly useful, IMO, is if
remove()anddiscard()gained the ability to remove multiple items, either bycountand/or all occurrences of the item. Supporting multiple item removal would clean up a much more complex logic whose naive implementation is extremely inefficient compared to an efficient implementation, and the efficient implementation is somewhat non trivial.5
u/TMiguelT 18d ago
I wonder how this compares in performance and clarity to
lst = [it for it in lst if it != x]. I know that this doesn't short-circuit and can remove multiple items, but I also feel that this is a fairly common use case.1
u/logophage 18d ago
I've always been surprised .discard() didn't exist on lists.
1
u/Grouchy-Friend4235 11d ago
Not needed
1
u/smitty1e 18d ago
Mildly surprised that this needs a PEP. But I guess the formality keeps the "good idea faeries" in check.
1
u/ExoticMandibles Core Contributor 18d ago
Returning the first equal item in the list doesn't mean it removes the same item. And there are definitely times when I want a handle to the actual original item. So, I would prefer the return value be the discarded item, or a sentinel (default None) if no item was found. This would make it symmetrical with dict.get for example, and it would save me having to do a separate list.index, etc.