[Python-ideas] get() method for list and tuples

David Mertz mertz at gnosis.cx
Tue Feb 28 12:18:53 EST 2017

On Tue, Feb 28, 2017 at 7:16 AM, Michel Desmoulin <desmoulinmichel at gmail.com
> wrote:

> Le 28/02/2017 à 15:45, Steven D'Aprano a écrit :
> > No you don't. You can use slicing.
> > alist = [1, 2, 3]
> > print(alist[99:100])  # get the item at position 99
> No this gives you a list of one item or an empty list.
> dict.get('key', default_value) let you get a SCALAR value, OR a default
> value if it doesn't exist.

    x = (alist[pos:pos+1] or [default_val])[0]

> How so ? "get the element x or a default value if it doesn't exist" seem
> at the contrary, a very robust approach.

Yes, and easily written as above.  What significant advantage would it have
to spell the above as:

    x = alist.get(pos, default_val)

It's a couple characters shorter in the proposed version.  I guess I'll
concede that needing the odd indexing at the end to get the scalar is
slightly ugly.

Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170228/39c0acd0/attachment-0001.html>

More information about the Python-ideas mailing list