PEP 851: Add list.discard()

Small things get added to Python all the time, so I don’t really understand your argument. Looking at the Python 3.15 release notes, I see

  • collections.Counter.__xor__(), collections.Counter.__ixor__()
  • re.prefixmatch()
  • os.statx()
  • mmap.mmap.set_name()
  • math.fmax(), math.fmin(), math.signbit()
  • dbm.sqlite3.reorganize()

I agree that the proposed name can be confusing and I’ve advocated for more explicit names, but other than that, I don’t see how the existence of this method harms anyone. You yourself didn’t know that set.discard() existed and were thus presumably never harmed by it.

9 Likes

Agreed. We get big changes, we get small changes. Every change has to justify itself based on how disruptive it is.

Adding a method to a built-in isn’t the smallest of changes, but it’s also far from the largest. There’s no syntactic changes, it’s easy to feature-test for, and it’s not going to conflict with any existing code. However, it also adds cognitive load to everyone who’s reading the list of methods, figuring out how to remove elements from a list (filter using a list comp, del lst[i], etc), and it gives more ways to do things.

Personally, I think that this IS worth those costs. But I can see why others disagree.

8 Likes

Okay, let me put it this way: One additional small thing won’t increase the complexity of Python. 1,000 additional small things will greatly increase the complexity of Python, especially for people learning the language. 1,000 additional tiny details is how you get Perl. Or Java or Rust. Or pretty much every programming language except Python.

The problem is that small changes are never seen as a problem, so we add it… and another… and another. Adding a list.discard is just a little bit of code. And a docstring. And documentation. And a note in the list.remove documentation about the difference. And the non-English translations of the documentation. And the unit tests. And another… and another…

(There’s a Joel Spolsky blog post about this, or maybe it was Raymond Chen, but I can’t find it. He was replying to someone about why the Win32 API couldn’t just create this one convenience function on top of some other API.)

Looking at the Python 3.15 release notes, I see

I checked those out, and I have some opinions (heh, some of them strong), but this thread isn’t about those and, well, they’re already in so we can’t take them out now. (Which, to reiterate, is why we have to be so excruciating even for “small” additions.)

And this isn’t adding a function to math or matching the statx system call: this is an addition to lists, the most prominent data structure in the Python language along with dictionaries.

You yourself didn’t know that set.discard() existed and were thus presumably never harmed by it.

Yes, but two things: 1) the fact that I’ve never encountered it before questions whether it’s all that useful in the first place if none of my coworkers/co-maintainers have ever written it and 2) it would be a problem if I had encountered it because I’d have to look up what it is. This is the Perl problem again: if there’s 5 ways to do something, you have to learn all 5 ways because your coworkers can use any of them. Ideally there should be one and only one way to do it.

Pathlib was a huge change, but brought a huge benefit. F-strings were a huge change (and we already had string concatenation and %s and the format() method!) but brought a huge benefit. Adding discard() is a small change for a small benefit. I don’t think that’s enough for a mature language like Python.

15 Likes

FTR,

  • For re.prefixmatch there was a long discussion, so we still decided to add it.
  • For math it’s because it was to complete the list of C99 functions that are also exposed by numpy and other math libs. I know that because I added them.
  • For the others, I don’t know.

I’m neutral on the list change personally. I’m worried about the return type (where None definitely doesn’t suit me) than the semantics. I think it makes sense to just have list.discard being like list.remove with the exception suppressed. Forget about whether it mimics set or not, it’s just different. Think of it as mimicking the “helpfulness” of the method and questions like “should it remove one, or all items” disappear.

Since list.remove made the choice of removing the first item if it exists adn raise otherwise, I believe list.discard should behave exactly the same but with the exception suppressed. If we need a method that removes everything then I think it’s better to use a list comprehension. I have barely needed to remove all occurrences of a specific element in place in a list, and if I needed to, I would re-assign the list contents in place as well via xs[:] = [xi for xi in xs if xi != x].

That being said, what I’d prefer is to know if my discard did anything instead of checking for the size of my list after the fact. Then I could do while xs.discard(x): ... instead (though AFAIR, I’ve never needed to use a list like that). For a set though it’s not really interesting so I don’t mind having a different return type because I can do while x in xs: xs.remove(x) for sets and have the same body afterwards and not worry too much about performances.

2 Likes

This is what bothers me most about this whole discussion. There are clearly many different use cases, and as a result people have many different views on what a discard function “should do”. It’s not at all clear to me why any one proposal is better than the others. And all of them can be implemented relatively simply in normal Python code.

So that’s my big question here - why is it so important that we go to all this effort of trying to establish which is the best interface, just so we can make that one a built in method? And how do we know that once we’ve done that, we won’t in future find ourselves going round the whole discussion again? After all, when list.remove was added, I assume that was considered the best API.

Is it so important that this particular functionality (whatever it is that we end up with) is built in? Why isn’t writing a helper function sufficient?

And that’s not a rhetorical question. We keep having discussions around these “small” additions to Python. There’s a common response, “not every 3-line function needs to be a builtin” - but it’s surprising to me just how many exceptions we seem to be willing to grant to that rule. Seriously, why do people not like writing helpers?

  • Is it because method syntax feels somehow better? Should we find a way to allow builtin types to be extended by user code?
  • Is it because it’s a pain to reuse little helpers like this? Should we be working to improve packaging to better handle this “tiny helpers too small to warrant a package of their own” use case? No-one wants a Javascript-style “left pad” situation, but maybe we can address the use case in a less problematic way?
  • Is it because people trust the core developers more than their own teams? Does “being built in” act as some sort of guarantee of quality that people value even for simple code? How do we explain that core dev time isn’t an infinite resource, and it should be spent on things that can’t be done by the end user?

I have no answers, and to an extent this is a much bigger question than this one proposal. But if we don’t ask it now, will we just continue to get “just one more” little addition, over and over again, until the sum total is an over-complex language that has lost the spirit of what attracted us all to Python in the first place?

18 Likes

I’ll give my personal take on this: I do see cases for “small change, small benefit”, when it makes the language more concise and doesn’t add sizable disadvantages for the users and maintainers.

With concise, I mean that you can clearly express the intent and it’s easy to write and understand.

Why a helper function may not be sufficient:

The PEP numbers state that about 15% of the most common packages use the currently available patterns. IMHO that’s common enough to justify at least considering a batteries-included solution but YMMV. OTOH, on average there are only 1.4 usages per package. I would consider it too much overhead to write a helper for 1-2 usages in my package. Likewise, I would not create an extra dependency and import for 1-2 usages.

Also, yes, mixing method and function is a bit of extra cognitive load: l.append(x); l.remove(x) is easier to follow than l.append(x); remove(l, x).

With respect to builtin types, neither user-extensibility nor third-party packages are helpful. There’s great value in a canonical set of well-designed functionality. In fact, I believe that this is one of the key success factors of Python.

Overall, I believe the imperfect current patterns are already better than a helper function. So to me the question is: a builtin solution or keep useing as is.

Can small changes be worth it?

By far not every small change is justifiable. But I strongly believe that many small improvements can add up to a significant improvement and a a net gain if the individual costs are well-considered.

PEP evaluation

I’ll go through the above discussed solutions to illustrate how such an evaluation may be done - of course judgement is subjective and you may come to other conclusions.

Need for a better solution

The PEP makes a valid point in the motivation that the current patterns have shortcomings. Concerning readability, I would say that both distract from the core operation of removing the element. In addition, the check-before-remove-pattern has extra runtime cost, and the exception pattern may catch other ValueErrors as well.

discard()

I’m still -1 on the proposed solution because discard() and remove() are semantically identical. This does not add clarity, so discard() should not be used, irrespective whether there could be an analogy to sets (which I also don’t find not a strong argument because sets are different enough so that analogies are limited; and discard should not have chosen for set in the first place either).

Other method

Even a well-named second function would be a -0 to me. It would be readable, but increases the API you have to learn. Not erroring is only a slight variation of behavior, not a completely different functionality.

Keyword argument

I would be +0.2 on an optional remove(missing_ok=True) parameter. That’s lighter than a separate function and there’s precedent for that pattern in Path.unlink. It’s not more than +0.2 because you may want to know whether something got removed, but adding a return value depending on the parameter is possibly more than we want.

ElementNotFoundError

I would be +0.5 on adding a ValueError subclass ElementNotFoundError so that one can write the exception case as:

try:
    lst.remove(x)
except ElementNotFoundError:
    pass

That improves readability (not as short as a oneliner, but very clear) and also removes the logic flaw that other ValueErrors might be caught.

No breaking changes

None of these solutions require deprecations or changes to existing code, which is prerequisite for the given context as the gain would not be high enough to justify changes to existing code.

Maintainer effort

I recognize that maintainer time is scarce and very valuable. For the present case, review and long-term maintainance effort are IMHO small compared to the up-front design and discussion. It’s maybe worth thinking about ways to further structure and streamline such discussions.

But unless we want to stictly limit idea input, that disuccion is necessary in one way or the other. Everybody can decide whether they want to join such conversations.

6 Likes

Otherwordly said, reduced cognitive dissonance.

The cost of a higher burden of choice for every time any user types list.<TAB> will surely not be compensated by the functionality of list.discard.

-1

I think a method like list.remove_if_exists[1] would be a good addition because it naturally guides people toward doing the right thing. The most common approach today is both slower and prone to unexpected failures. If anything, I’d argue that the status quo goes against Python’s philosophy of being approachable. Python currently leads users toward a slightly suboptimal solution, and it’s only when they dig deeper that they discover there’s a better way to accomplish what they wanted in the first place.


  1. as others have pointed out, discard is practically a synonym for remove, so it’s a suboptimal name. ↩︎

4 Likes

Thanks for the reply and after thinking a bit more I lean more towards -1 rather than 0 or +0.5 (for this specific proposal).

This is what bothers me most about this whole discussion. There are clearly many different use cases, and as a result people have many different views on what a discard function “should do”. It’s not at all clear to me why any one proposal is better than the others. And all of them can be implemented relatively simply in normal Python code.

Well.. I don’t see what we can return other than (1) the item (but that’s not possible because what should we return if it’s not removed? by “item”, I really mean the ref being stored by the list, not the one we use for == testing) (2) true/false to determine if the operation did anything (3) or nothing (like list.remove()).

list.remove() could have returned the item (because if it doesn’t exist, we raise an exception) or None. We chose to return nothing, likely because it wasn’t deemed interesting to get the ref of the removed item (if we needed it, then we should likely find it by index first and then delete it via del xs[i]). But this doesn’t mean we can’t choose something else for a hypothetical discard(). So don’t take the “I want a boolean returned” as a condition for my support.

but it’s surprising to me just how many exceptions we seem to be willing to grant to that rule

Maybe I’m saying obvious things, but I don’t think we should use that rule as a hard stop. It makes sense most of the time, but not always IMO. Even 3-line helpers can be hard to write.

Seriously, why do people not like writing helpers?

Some helpers are harder to write or require you to have them either as project dependency or by duplicating them across all projects (which is exactly the same as having an internal dependency in some sense). And people likely trust the stldib to implement their helpers faithfully. I believe that’s also why some recipes in itertools.rst were moved to actual itertools functions (e.g., pairwise or batched, though those are the only ones I’m aware of).


But let’s compare apples-to-apples. We are talking about a new built-in methods. Builtins had few additions these past years but those are the ones that I remember on top of my head:

  • str.removeprefix, str.removesuffix: these are also clearly one-line helpers.
  • int.is_integer: solely added for duck compatibility with float.is_integer
  • float.from_number/complex.from_number: added because it’s not that trivial for converting numbers in general
  • addition of strict keyword for map because zip had one (and this required a PEP as well).

I see the addition of list.discard equivalent to the addition of str.removeprefix and str.removesuffix. It’s not necessarily needed, but it’s convenient to have it when you need it.


My (new) issue with the proposal though is the argument about “it’s helpful to avoid issues when ValueError is raised from __eq__”. Code free of bug is usually not meant to raise such exceptions (and usually __eq__ are cheap methods or default ones). But I may be wrong here.

Now, I would rather support subclassing ValueError for such cases so that don’t need to introduce a new method, much like ModuleNotFoundError which is a special subclass of ImportError that can be caught for finer control. It could serve not only in finer control of list.remove() exceptions but also in any other extension modules that may raise ValueError (such as the XML module) and one doesn’t know whether ValueError is due to an issue in __eq__ or elsewhere. Any “remove-like” operation that tests for existence first could use that new exception and we wouldn’t be limited in the future.


While list.discard may have some reasons to exist, I don’t see why I would want deque.discard which was proposed in the same issue. A deque for me is just a way to efficiently pop from the ends. I never need to remove an item from inside my deque. The asymmetry with the lack of a non-raising index() also bothers me. I wished index() actually returned -1 instead of a ValueError when an item doesn’t exist but it’s no longer possible to change that since it comes from the Sequence protocol. I find it a bit weird as well that list would be the only mutable sequence with a non-raising remove().

1 Like

I think a method like list.remove_if_exists would be a good addition because it naturally guides people toward doing the right thing.

Naming things is hard, and when we have deep familiarity we forget how it looks to beginners and outsiders. remove_if_exists() makes sense to me, because I know that remove()raises an exception if the item doesn’t exist in the list.

But if we step back and take the perspective of someone without this info, remove_if_exists() is a tautology: of course we remove it if it exists, because we wouldn’t remove it if it didn’t exist.

The unstated bit is what to do if it doesn’t exist, and it isn’t clear from the name alone. To someone new to Python, remove_if_exists() can mean:

  • “Remove this item if it exists, and raise an exception if it doesn’t.”
  • “Remove this item if it exists, but don’t raise an exception if it doesn’t.”

And you can’t tell without consulting the documentation, which is something a good name helps users avoid.

Seriously, why do people not like writing helpers?

I can only speculate, but there is something unsatisfying about having a bloated utils.py in your project. I think the common misstep we make is thinking that just because it’s a common enough need for us to write a helper or wrapper function, it’s common enough need for all of the millions of Python developers.

3 Likes

Perhaps, but it is a very strong general principle across programming (and even non-programming) that “if exists” (or if anything else) means “otherwise don’t”. So it’s “remove if it exists, otherwise don’t”. Go to the shops, get a loaf of bread; if they have eggs, get a dozen. [1] If they don’t have eggs, that’s okay, just come home without any; if they don’t have bread, that’s a problem and maybe figure out an alternative [2].


  1. A programmer comes home with 12 loaves of bread because they did in fact have eggs - a normal person comes home with 1 loaf of bread and a dozen eggs. ↩︎

  2. brioche, if this is the French Revolution ↩︎

4 Likes

I think the “why not a helper” bit is even a red herring here.

There’s no reason why

try:
    some_list.remove(might_not_exist)
except ValueError:
    pass

can’t be written inline when that’s actually the intent. It doesn’t need a helper. This has no time of check time of use issue, nor is it scanning the list twice. (both of which are issues if you check then remove)

4 Likes

Sure, but my point is that remove() also means “remove if it exists, otherwise don’t.” Someone who is new to Python will see that lists have remove() and remove_if_exists() methods, and have to check the docs for what they actually mean. (Then we’re back to the original problem with remove() and discard().)

1 Like

If you can see both of them, then clearly one of them is “remove conditionally on it existing” and the other is “remove unconditionally”, which must therefore fail if it does NOT exist. Granted, if you only saw remove() on its own, you wouldn’t know that, but with both of them visible, the semantics are clear.

4 Likes

TL;DR: I’m -1 to any list.remove_xxx

As I mentioned earlier, I’m not particularly interested in list.discard, but I’ve read some oppositions to it because n English remove and discard have the same meaning.

So what about dict[key] and dict.get(key)? dict[key] is not English, but it can be translated as “get the value corresponding to key from dict”.

IMO ergonomics are important. What if I wanted to implement a function that accepts a set or a list and discards an element? It’s easier and more elegant to write[1]:

def discard(cont: list | set, elem) -> bool:
    return cont.discard(elem)

than

def discard(cont: list | set, elem) -> bool:
    if isinstance(cont, list):
        return cont.remove_xxx(elem)
    return cont.discard(elem)

I don’t like list.remove_all too. I think remove(all=False) is definitely better. Yes, this makes the method’s signature different from that of set, and that’s fine! set.remove(all=True) doesn’t make sense.


  1. assuming that set.discard will return a bool indicating whether the element is removed or not ↩︎

1 Like

It’s the wrapper’s job to deal with whatever they are wrapping and their differences. And this symmetry immediately breaks again if say you wanna add an element:

def add(cont: list | set, elem) -> bool:
    if isinstance(cont, list):
        return cont.append(elem)
    return cont.add(elem)

We should be optimizing for what works best for list first and foremost.

4 Likes

Actually I said I prefer adding a list.add alias for list.append rather than a discard.

It’s not a matter of symmetry. There’s no symmetry here. set.discard and list.discard are really different. But de facto list.remove is used instead of set.remove in many cases.

So, if Python wanted to introduce a list.discard, the fact doesn’t really matter to me. But if we wanted to name it list.remove_whatever, well, please, please no.

I think this is quite likely. The packaging infrastructure requires a fair amount of boilerplate, much of which is overkill for minor things like this. In addition, it is based around the idea of deciding first that you are going to write a package[1], which is not conducive to situations where you are fiddling around with code and find yourself with some little snippet you want to reuse. At least for me, the case of “I’m just trying stuff out and don’t want to make a package right now” is often correlated with “I find I’ve written some little snippet that I might like to use again”.

I’m not sure exactly what a solution to this would look like, but I’ve often wanted a “packaging-last” approach, in which I can get a bunch of code working and usable and then afterwards make a package out of it, instead of having to start with the packaging part.

I have a hunch that with a lot of these little snippets, people don’t have any intention of distributing them publicly. They just want to be able to reuse them themselves. So a leftpad situation is not so likely to arise if there is a convenient way for them to do that.


  1. For instance, pretty much the first thing in the tutorial is “Create the following file structure locally”. ↩︎

For that use case, just shoving a .py file in a local directory and setting PYTHONPATH to that directory should be enough.

As to why people don’t do that, I suspect it’s because people don’t like having to fiddle with environment variables? Or maybe there’s a fear that globally changing where Python searches for modules “might break something”?

There’s user-site, but maybe that feels like it’s more for “proper packages” than simple .py files?

I’m guessing again, though. Why don’t people use user-site (or a personal directory) for this sort of thing? Can anyone who has wanted a small utility function enough to propose it for the stdlib explain why they don’t just add it to user-site?

1 Like

I would probably never create a global helper file like that, because as soon as I share the code with someone, move it to a different environment, or upload it, the library with my custom functions is gone. Maybe I’d do a hard- or sym-link, but it’s still a bit of a hassle.

3 Likes