What would list.discard add to Python?

November 17, 2026 5 answers
Asked by Vexlori-5b

I saw a proposal for list.discard. How would it differ from list.remove, and is it useful enough to add?

Answers

c.368+frostladle

The proposal would remove the first item equal to the argument and return True. If nothing matches, it would leave the list alone and return False. Unlike list.remove, it would not raise ValueError just because the item is missing.

That gives you a concise way to attempt the removal and check whether it worked. The name follows set.discard, though the proposed list method has a Boolean return value.

Reply to this answer
_v6!prindle.8

The existing options have tradeoffs. Checking membership before calling remove is readable, but on a hit it searches twice. If another thread changes the list between those calls, remove can still fail.

A try and except around remove avoids the separate membership check, but catching ValueError can also hide a ValueError raised by an item's equality comparison. A dedicated method would make the intended missing-item case clearer.

Reply to this answer
_k64+veldrin.7

I can see the appeal, but this feels like a small convenience rather than a major missing feature. Suppressing ValueError around remove already handles the common missing-item case, although it has the same risk of catching an error from a comparison.

There's also a design question about whether removing just the first equal item is what people expect from a list operation.

Reply to this answer
_f58+norvexa.2

Watch out for duplicates. A comprehension that keeps items unequal to x removes all matching items, while the proposed discard removes only the first. Reassigning the comprehension result also creates a new list, so other references to the original list won't see that change.

A separate remove-all operation could be useful, but that's a different behavior from this proposal.

Reply to this answer
Tervixo.9p

Another idea is a missing_ok argument on remove, but the return value makes that awkward. remove currently returns None, while the proposed discard reports success. Changing remove's return behavior, or making it depend on a flag, would be a different API choice.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions