From 1514264fd99ab48e8906fe288ff8e0b8996f7c4b Mon Sep 17 00:00:00 2001 From: Stan Ulbrych Date: Tue, 27 Oct 2026 08:55:09 +0000 Subject: [PATCH 1/3] Add PEP 851 --- .github/CODEOWNERS | 1 + peps/pep-0851.rst | 166 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 peps/pep-0851.rst diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index db43aa2a2b8..944a91ed755 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -729,6 +729,7 @@ peps/pep-0848.rst @markshannon peps/pep-0849.rst @JelleZijlstra peps/pep-0850/ @willingc @rgommers peps/pep-0850.rst @willingc @rgommers +peps/pep-0851.rst @StanFromIreland # ... peps/pep-2026.rst @hugovk # ... diff --git a/peps/pep-0851.rst b/peps/pep-0851.rst new file mode 100644 index 00000000000..3d63123d7b8 --- /dev/null +++ b/peps/pep-0851.rst @@ -0,0 +1,166 @@ +PEP: 851 +Title: Add list.discard() +Author: Stan Ulbrych +Discussions-To: Pending +Status: Draft +Type: Standards Track +Created: 26-Oct-2026 +Python-Version: 3.16 +Post-History: `12-Oct-2025 `__ + + +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()``, as +``set.discard()`` is to ``set.remove()``. + + +Motivation +========== + +Removing a value that may not be present is currently `usually written as +`__:: + + if x in lst: + lst.remove(x) + +or:: + + try: + lst.remove(x) + except ValueError: + pass + +The 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 [#search]_ +finds 1,062 matches for the first form across 411 projects and 331 for +the second across 164 projects (a small fraction of these will be on other +container types). Excluding tests, the standard library contains +7 and 20 respectively 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()``. + + +Specification +============= + +``list`` gains a positional-only method ``discard(value, /)``. It removes +the first item equal to *value* and returns ``True``, or returns ``False`` +if there is no such item. Only the absence of a matching item is reported +by the return value; any other error, including a ``ValueError`` raised +during equality comparison, propagates as an exception. The implementation +shares the search loop of ``remove()``, so which item is removed, how +values are compared and the thread-safety properties are identical to +``remove()``. ``collections.UserList`` gains the same method for consistency. + + +Rationale +========= + +The name follows the ``remove()`` / ``discard()`` distinction already +made by ``set``, where ``discard()`` is the variant that tolerates a +missing item. It has been raised that ``s.discard(x)`` guarantees +``x not in s`` afterwards, while ``lst.discard(x)`` does not if *x* +appears more than once. This is a real difference. ``discard()`` +deliberately shares the search and removal semantics of ``list.remove()`` +rather than those of ``set.discard()``, and the documentation states this +explicitly. The name remains the least surprising choice as users who know +sets can apply that knowledge directly. + +Unlike ``set.discard()``, which returns ``None``, a bool is returned +(thanks to Guido van Rossum for the suggestion). This costs nothing, since +the implementation already knows the outcome, and lets +``if lst.discard(x):`` replace the double scan for callers who care. + +``deque.discard()`` is a possible follow-up if this PEP is accepted. + + +Backwards Compatibility +======================= + +``list`` subclasses defining their own ``discard`` keep it. Code using +``hasattr(obj, "discard")`` to tell sets from lists would be affected. +None was found in the standard library or the top 5,000 PyPI packages. + + +How to Teach This +================= + +Introduce it in the tutorial directly after ``remove()``, with ``remove()`` +for when the item must be present and ``discard()`` for when it may not +be. The same pairing already exists for sets. + + +Reference Implementation +======================== + +A reference implementation can be found in `python/cpython#160726 +`__. + + +Rejected Ideas +============== + +A parameter on ``remove()`` +--------------------------- + +A separate method is preferred over a parameter such as +``remove(x, missing_ok=True)``. The standard library has precedent for both +shapes, ``Path.unlink(missing_ok=True)`` and ``os.makedirs(exist_ok=True)`` +on one side and ``set.remove()`` / ``set.discard()`` on the other, but the +closest precedent is ``set``, and following it means the two container +types share one vocabulary. A method also reads clearer at the call site, +since ``lst.discard(x)`` says what happens while a flag describes what +does not. + +Adding ``discard()`` to ``collections.abc.MutableSequence`` +----------------------------------------------------------- + +``collections.abc.MutableSequence`` is left unchanged, as is the case for +``list.copy()``. Adding ``discard()`` to the ABC would change the interface +of every third-party subclass, while virtual subclasses registered with +``register()`` would not gain it at all. + + +Footnotes +========= + +.. [#search] Using `Victor Stinner's scripts + `__, + modified to match across lines, with the regular expressions:: + + if ([\w.\[\]]+) in ([\w.\[\]]+):\n\s+\2\.remove\(\1\) + + try:\n\s+([\w.\[\]]+)\.remove\(([\w.\[\]]+)\)\n\s*except ValueError: + + The first pattern's backreferences require the same names on both + lines. The counts are approximate, as the second pattern also matches + handlers that do something other than ignore the absence, while neither + matches variants such as compound conditions, + ``except (ValueError, ...)`` or a comment between the lines. + + +Copyright +========= + +This document is placed in the public domain or under the +CC0-1.0-Universal license, whichever is more permissive. From 28ac34cdc3bbcf040e68a4d28dccc454462c1480 Mon Sep 17 00:00:00 2001 From: Stan Ulbrych Date: Tue, 27 Oct 2026 10:04:41 +0000 Subject: [PATCH 2/3] s/gaurantees/holds/ --- peps/pep-0851.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/peps/pep-0851.rst b/peps/pep-0851.rst index 3d63123d7b8..1ffb6e3f040 100644 --- a/peps/pep-0851.rst +++ b/peps/pep-0851.rst @@ -78,8 +78,8 @@ Rationale The name follows the ``remove()`` / ``discard()`` distinction already made by ``set``, where ``discard()`` is the variant that tolerates a -missing item. It has been raised that ``s.discard(x)`` guarantees -``x not in s`` afterwards, while ``lst.discard(x)`` does not if *x* +missing item. It has been raised that after ``s.discard(x)`` the test +``x not in s`` holds, while after ``lst.discard(x)`` it need not if *x* appears more than once. This is a real difference. ``discard()`` deliberately shares the search and removal semantics of ``list.remove()`` rather than those of ``set.discard()``, and the documentation states this From 52d855dd720fe62802293688df5e197344b55c02 Mon Sep 17 00:00:00 2001 From: Stan Ulbrych Date: Tue, 27 Oct 2026 10:18:59 +0000 Subject: [PATCH 3/3] Address Hugo's review Co-authored-by: Hugo van Kemenade --- peps/pep-0851.rst | 96 +++++++++++++++++++++++++++++------------------ 1 file changed, 60 insertions(+), 36 deletions(-) diff --git a/peps/pep-0851.rst b/peps/pep-0851.rst index 1ffb6e3f040..555ac8f4ac4 100644 --- a/peps/pep-0851.rst +++ b/peps/pep-0851.rst @@ -4,7 +4,7 @@ Author: Stan Ulbrych Discussions-To: Pending Status: Draft Type: Standards Track -Created: 26-Oct-2026 +Created: 27-Oct-2026 Python-Version: 3.16 Post-History: `12-Oct-2025 `__ @@ -14,14 +14,14 @@ 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()``, as -``set.discard()`` is to ``set.remove()``. +removed. It is the non-raising counterpart to :meth:`list.remove`, as +:meth:`set.discard` is to :meth:`set.remove`. Motivation ========== -Removing a value that may not be present is currently `usually written as +Removing a value that may not be present is `usually written as `__:: if x in lst: @@ -36,17 +36,18 @@ or:: The 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 +two calls, turning a no-op into a :exc:`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__``. +user-defined :meth:`~object.__eq__`. Both are common. A search of the 5,000 most downloaded PyPI projects [#search]_ finds 1,062 matches for the first form across 411 projects and 331 for -the second across 164 projects (a small fraction of these will be on other -container types). Excluding tests, the standard library contains -7 and 20 respectively on lists, for example in `logging +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 `__, @@ -57,7 +58,7 @@ 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()``. +search and removal implementation of :meth:`remove() `. Specification @@ -66,11 +67,12 @@ Specification ``list`` gains a positional-only method ``discard(value, /)``. It removes the first item equal to *value* and returns ``True``, or returns ``False`` if there is no such item. Only the absence of a matching item is reported -by the return value; any other error, including a ``ValueError`` raised +by the return value; any other error, including a :exc:`ValueError` raised during equality comparison, propagates as an exception. The implementation -shares the search loop of ``remove()``, so which item is removed, how -values are compared and the thread-safety properties are identical to -``remove()``. ``collections.UserList`` gains the same method for consistency. +shares the search loop of :meth:`remove() `, so which item is +removed, how values are compared and the thread-safety properties are +identical to ``remove()``. :class:`collections.UserList` gains the same +method for consistency. Rationale @@ -81,33 +83,39 @@ made by ``set``, where ``discard()`` is the variant that tolerates a missing item. It has been raised that after ``s.discard(x)`` the test ``x not in s`` holds, while after ``lst.discard(x)`` it need not if *x* appears more than once. This is a real difference. ``discard()`` -deliberately shares the search and removal semantics of ``list.remove()`` -rather than those of ``set.discard()``, and the documentation states this -explicitly. The name remains the least surprising choice as users who know +deliberately shares the search and removal semantics of :meth:`list.remove` +rather than those of :meth:`set.discard`, and the documentation for +``list.discard()`` in the reference implementation states this explicitly. +The name remains the least surprising choice as users who know sets can apply that knowledge directly. -Unlike ``set.discard()``, which returns ``None``, a bool is returned -(thanks to Guido van Rossum for the suggestion). This costs nothing, since -the implementation already knows the outcome, and lets +Unlike :meth:`set.discard`, which returns ``None``, a bool is returned. This +costs nothing, since the implementation already knows the outcome, and lets ``if lst.discard(x):`` replace the double scan for callers who care. -``deque.discard()`` is a possible follow-up if this PEP is accepted. - Backwards Compatibility ======================= -``list`` subclasses defining their own ``discard`` keep it. Code using +:class:`list` subclasses defining their own ``discard`` keep it. Code using ``hasattr(obj, "discard")`` to tell sets from lists would be affected. None was found in the standard library or the top 5,000 PyPI packages. +Security Implications +===================== + +None. + + How to Teach This ================= -Introduce it in the tutorial directly after ``remove()``, with ``remove()`` -for when the item must be present and ``discard()`` for when it may not -be. The same pairing already exists for sets. +Introduce it in the `tutorial +`__ +directly after :meth:`list.remove`, with ``remove()`` for when the item +must be present and ``discard()`` for when it may not be. The same pairing +already exists for :class:`set`. Reference Implementation @@ -125,20 +133,29 @@ A parameter on ``remove()`` A separate method is preferred over a parameter such as ``remove(x, missing_ok=True)``. The standard library has precedent for both -shapes, ``Path.unlink(missing_ok=True)`` and ``os.makedirs(exist_ok=True)`` -on one side and ``set.remove()`` / ``set.discard()`` on the other, but the -closest precedent is ``set``, and following it means the two container -types share one vocabulary. A method also reads clearer at the call site, -since ``lst.discard(x)`` says what happens while a flag describes what -does not. +shapes, :meth:`Path.unlink(missing_ok=True) ` and +:func:`os.makedirs(exist_ok=True) ` on one side and +:meth:`set.remove` / :meth:`set.discard` on the other, but the closest +precedent is ``set``, and following it means the two container types share +one vocabulary. A method also reads more clearly at the call site, since +``lst.discard(x)`` says what happens while a flag describes what does not. Adding ``discard()`` to ``collections.abc.MutableSequence`` ----------------------------------------------------------- -``collections.abc.MutableSequence`` is left unchanged, as is the case for -``list.copy()``. Adding ``discard()`` to the ABC would change the interface -of every third-party subclass, while virtual subclasses registered with -``register()`` would not gain it at all. +:class:`collections.abc.MutableSequence` is left unchanged, as is the case +for :meth:`list.copy`. Adding ``discard()`` to the ABC would change the +interface of every third-party subclass, while virtual subclasses +registered with ``register()`` would not gain it at all. + +``deque.discard()`` +------------------- + +The `original discussion +`__ +also proposed :class:`collections.deque` gaining the same method. It is +left out of this PEP to keep the proposal to the builtin :class:`list`. +It can follow as a routine change if this PEP is accepted. Footnotes @@ -159,6 +176,13 @@ Footnotes ``except (ValueError, ...)`` or a comment between the lines. +Acknowledgements +================ + +Thanks to Guido van Rossum for suggesting that ``discard()`` return whether +an item was removed. + + Copyright =========