On Wed, Oct 31, 2018 at 02:25:25AM +0200, Serhiy Storchaka wrote:
> 31.10.18 01:44, Giampaolo Rodola' пише:
> >Sorry in advance if this has been proposed in the past but I couldn't
> >find anything on python-ideas:
> >
> > >>> l = []
> > >>> l.pop(default=1)
> >1
[...]
> It is just
>
> l.pop() if l else default
It might *do* the same thing, but it doesn't communicate the
programmer's intention as well.
{}.pop('key', default) could be written using LBYL too, but the
intention is much clearer given an explicit default argument.
The only advantage of the "if l" version is that if the default is
expensive to calculate, we can short-circuit it.
> or
>
> (l or [default]).pop()
That's clever, but it is also wasteful, building a single-item list only
to immediately pop the item out of it and throw the list away.
[steve@ando ~]$ python3.5 -m timeit -s "l = []" "l.pop() if l else None"
10000000 loops, best of 3: 0.0739 usec per loop
[steve@ando ~]$ python3.5 -m timeit -s "l = []" "(l or [None]).pop()"
1000000 loops, best of 3: 0.421 usec per loop
--
Steve
_______________________________________________
Python-ideas mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/