[Python-ideas] Add "default" kwarg to list.pop()
Steven D'Aprano
steve at pearwood.info
Fri Nov 2 06:26:35 EDT 2018
On Thu, Nov 01, 2018 at 09:36:19PM +0200, Serhiy Storchaka wrote:
> 31.10.18 13:07, Antoine Pitrou пише:
> >l.pop(default=...) has the potential to be multi-thread-safe, while
> >your alternatives haven't.
>
> The multi-thread-safe alternative is:
>
> try:
> value = l.pop()
> except IndexError:
> value = default
That's not an expression, so there are limits to where and when you can
use it. What we need is a helper function that wraps that, called "pop".
And since this seems to be reoccuring request going back nearly 20 years
now:
https://mail.python.org/pipermail/python-dev/1999-July/000550.html
https://stackoverflow.com/questions/31216428/python-pop-from-empty-list
as is the more general get(list, index, default=None) helper:
https://stackoverflow.com/questions/2574636/getting-a-default-value-on-index-out-of-range-in-python
https://stackoverflow.com/questions/2492087/how-to-get-the-nth-element-of-a-python-list-or-a-default-if-not-available
https://stackoverflow.com/questions/5125619/why-doesnt-list-have-safe-get-method-like-dictionary
https://stackoverflow.com/questions/17721748/default-value-for-out-of-bounds-list-index
we could save people from having to re-invent the wheel over and over
again by add them to a new module called
"things_that_should_be_list_methods_but_arent.py"
*wink*
--
Steve
More information about the Python-ideas
mailing list