Repository navigation
PEP 851: Add list.discard() #5200
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,190 @@ | ||
| PEP: 851 | ||
| Title: Add list.discard() | ||
| Author: Stan Ulbrych <stan@python.org> | ||
| Discussions-To: Pending | ||
| Status: Draft | ||
| Type: Standards Track | ||
| Created: 27-Oct-2026 | ||
| Python-Version: 3.16 | ||
| Post-History: `12-Oct-2025 <https://discuss.python.org/t/add-list-discard-and-deque-discard/104330>`__ | ||
|
|
||
|
|
||
| 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 :meth:`list.remove`, as | ||
| :meth:`set.discard` is to :meth:`set.remove`. | ||
|
|
||
|
|
||
| Motivation | ||
| ========== | ||
|
|
||
| Removing a value that may not be present is `usually written as | ||
| <https://stackoverflow.com/questions/4915920/how-to-delete-an-item-in-a-list-if-it-exists>`__:: | ||
|
|
||
| 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 :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 :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. 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 | ||
| <https://github.com/python/cpython/blob/3acc941f2b7288b212a4163ab21aa79faff9cd13/Lib/logging/__init__.py#L840-L841>`__, | ||
| `warnings <https://github.com/python/cpython/blob/3acc941f2b7288b212a4163ab21aa79faff9cd13/Lib/_py_warnings.py#L326-L329>`__, | ||
| `tkinter <https://github.com/python/cpython/blob/3acc941f2b7288b212a4163ab21aa79faff9cd13/Lib/tkinter/__init__.py#L490-L493>`__, | ||
| `runpy <https://github.com/python/cpython/blob/3acc941f2b7288b212a4163ab21aa79faff9cd13/Lib/runpy.py#L312-L315>`__ and | ||
| `asyncio <https://github.com/python/cpython/blob/3acc941f2b7288b212a4163ab21aa79faff9cd13/Lib/asyncio/subprocess.py#L100-L101>`__. | ||
| 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 :meth:`remove() <list.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 :exc:`ValueError` raised | ||
| during equality comparison, propagates as an exception. The implementation | ||
| shares the search loop of :meth:`remove() <list.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 | ||
| ========= | ||
|
|
||
| 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 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 :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 :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. | ||
|
|
||
|
|
||
| Backwards Compatibility | ||
| ======================= | ||
|
|
||
| :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 | ||
| <https://docs.python.org/3/tutorial/datastructures.html#more-on-lists>`__ | ||
| 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 | ||
| ======================== | ||
|
|
||
| A reference implementation can be found in `python/cpython#160726 | ||
| <https://github.com/python/cpython/pull/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, :meth:`Path.unlink(missing_ok=True) <pathlib.Path.unlink>` and | ||
| :func:`os.makedirs(exist_ok=True) <os.makedirs>` 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`` | ||
| ----------------------------------------------------------- | ||
|
|
||
| :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 | ||
| <https://discuss.python.org/t/add-list-discard-and-deque-discard/104330>`__ | ||
| 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 | ||
| ========= | ||
|
|
||
| .. [#search] Using `Victor Stinner's scripts | ||
| <https://hugovk.dev/blog/2022/how-to-search-5000-python-projects/>`__, | ||
| 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. | ||
|
|
||
|
|
||
| Acknowledgements | ||
| ================ | ||
|
|
||
| Thanks to Guido van Rossum for suggesting that ``discard()`` return whether | ||
| an item was removed. | ||
|
|
||
|
|
||
| Copyright | ||
| ========= | ||
|
|
||
| This document is placed in the public domain or under the | ||
| CC0-1.0-Universal license, whichever is more permissive. | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.