r/Python • u/kirara0048 • 28d 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().
20
u/chaz6 28d 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 as def discardall(self, x).
13
u/droans 28d ago
discardallprobably would make more sense.
discardwould return a bool if the item was present butdiscardallcould return an int representing the number of items discarded.7
u/yvrelna 28d ago edited 26d ago
Since we're bike shedding this, personally my preference would be
list.discard(item[, start[, stop]], /, count=1, start=0, stop=)(and likewise withlist.remove()).Where if you pass a sentinel like
-1orNoneor maybe a special constantlist.ALL, then it becomes discard all.
startandstopwould limit the range where the removal is allowed to happen, with similar semantic tolist.index().2
u/staticcast 28d ago
We're not full c++ bikeshedding yet: let's also create an interface that takes comparison lambda, and another one that doesn't really discard item but instead place them in a way that you can then call erase to actually delete them.
1
u/RingularCirc 25d ago
No need for lambdas, just create a proxy object that has its "equality" redefined to be that coarser comparison.
(And on a serious note,
pytest.approxis exactly that! There, it's useful for writing tests for floats when your numeric code isn't too imprecise.)1
u/Outside_Complaint755 24d ago
You could just do
while my_list.discard(x): passto discard all instances. A bit of a smell, but concise.
21
u/XtremeGoose f'I only use Py {sys.version[:3]}' 28d 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.
1
u/AKSrandom 26d ago
I do not get how a dictionary with None values would help the ordering requirement, pls elaborate
2
u/XtremeGoose f'I only use Py {sys.version[:3]}' 26d ago
Dictionaries maintain their insertion order since python 3.7, sets do not. You can also think of sets as dictionaries without any meaningful mapping. So in some sense you could do
type OrderedSet[T] = dict[T, None]3
u/RingularCirc 25d ago
Can't have a clue why both of you got downvoted: bothe the question and the answer are reasonable (not everybody knows that
dictconserves insertion order, and there are only a few things that are mandatory to know in this life; "obvious" is different for everyone).
13
5
u/Oddly_Energy 28d ago edited 28d 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):
9
1
u/RevRagnarok 28d ago
removes the first item equal to x
PEP doesn't say if that was considered; only that the return boolean flag was suggested by BDFL.
12
u/yvrelna 28d ago edited 28d ago
This proposal is a -0 from me. The proposed discard semantic is just a syntax sugar for:
with suppress(ValueError):
lst.remove(item)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() and discard() gained the ability to remove multiple items, either by count and/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.
9
u/yvrelna 28d ago
I also liked Chris Markiewicz's point there in the Discourse thread. The proposed
list.discard()method feels iffy because the originallist.remove()was also iffy.list.remove()removing only the first item in the list was not a natural kind of operation that you often want to do in a list.Removing an item from a list, and treating a list like a bag of objects is a weird use case for a list and the current
remove()API was kinda underpowered if it actually needs to perform what it needed to do in a list.1
u/pingveno pinch of this, pinch of that 28d ago
Maybe I'm misreading things, but isn't that explicitly the opposite of the semantics of the PEP? It is just testing equality, and ValueError propagates just fine. Something like:
for i in range(len(lst)): if item == lst[i]: del lst[i] return True else: return False
5
u/TMiguelT 28d 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.
5
u/UnMolDeQuimica 28d ago
Given OP explanation,
discardwould only remove the first item of that kind. For example[3, 1, 9, 5, 1].discard(1)would become[3, 9, 5, 1].Your example would remove both entries for
1.To me, discard makes sense but we would need another mirror method that removes all the entries except the first one or the last one.
-1
u/RevRagnarok 28d ago
need another mirror method
It returns whether it was found or not:
while my_list.discard(1): pass3
2
u/yvrelna 28d ago edited 28d ago
That is
O(n**2).An efficient in-place, multi-item discard should've been able to do this in
O(n)and without making an in-memory copy.Currently, the best idiomatic way to do multi item discard is the list comprehension, but it makes a copy and it's not in-place operation.
So a slightly better implementation of multi-inplace discard is
lst[:] = [it for it in lst if it != x]It creates an in-memory copy, which doubles the memory requirement, but IMO, that's a much less egregious sin than
O(n**2)operation.There's still no idiomatic way to efficiently do multi item discard, AFAICT, even after this proposal.
-2
3
u/Ball-Man 28d ago
As you said, this is a different operation, though related. Performance wise it's almost guaranteed that the c implementation of list.discard will be more efficient. Clarity wise, list.discard is self explanatory, just read the name of the method. This comprehension is simple but you don't have a clear name for it, I still have to take extra time to "parse it" in my mind.
2
u/RevRagnarok 28d ago
This creates a new
listand assignslstto it. Iflstwas given to you, the caller will never see the change. That's a big deal to those learning the language.
1
1
1
u/smitty1e 28d ago
Mildly surprised that this needs a PEP. But I guess the formality keeps the "good idea faeries" in check.
4
u/Oddly_Energy 28d ago
It seems like a good way of ensuring some structure around a suggestion. And a good way of tracking suggestions.
3
u/yvrelna 28d ago
One of the most underappreciated reason for proposing a PEP is actually also to track rejection.
If an oft-proposed idea keeps being proposed, the dev can just point to the existing PEP and you'd have to justify if there's anything that substantially changed since the last time it got rejected.
2
u/JanEric1 28d ago
There was a discussion whether one is needed in the discuss thread or the issue but the author just opted to do one before that came to a final conclusion I think
1
u/ExoticMandibles Core Contributor 28d 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.
96
u/Brilliant_Cut_8780 28d 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.