This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: dict get() function equivalent for lists.
Type: enhancement Stage: resolved
Components: Versions:
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: feluxe, rhettinger, serhiy.storchaka
Priority: normal Keywords:

Created on 2018-03-01 16:52 by feluxe, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (4)
msg313099 - (view) Author: Felix (feluxe) Date: 2018-03-01 16:52
Hi there!

I hope this wasn't suggested before. I couldn't find any issues related to it.

The `get()` function on the dictionary object is such a convenient way for retrieving items from a dict that might not exists. I always wondered why the list object does not have an equivalent?

I constantly run into something like this:

    myval = mylist[1] if len(mylist) > 1 else None

or worse like this:

    try:
        myval = mylist[1]
    except IndexError:
        myval = None

While I think it would be nice to do it like this:

    myval = mylist.get(1)

Any love for this?

Cheers! :)
msg313101 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2018-03-01 17:09
It was suggested a year ago. See the topic "get() method for list and tuples" on the Python-ideas mailing list.

https://mail.python.org/pipermail/python-ideas/2017-February/044839.html
msg313104 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2018-03-01 18:47
Yes, this was discussed and rejected several years ago.

Thank you for the suggestion.
msg313106 - (view) Author: Felix (feluxe) Date: 2018-03-01 18:58
Thanks for the link! Interesting read.

I have to disagree with the statement that this is something that happens very rarely. Just have a look at the mess on stackoverflow alone (these are only the top results I got after a minute of googling):

https://stackoverflow.com/questions/5125619/why-doesnt-list-have-safe-get-method-like-dictionary

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/2574636/getting-a-default-value-on-index-out-of-range-in-python

https://stackoverflow.com/questions/12186388/get-value-at-list-array-index-or-none-if-out-of-range-in-python

https://stackoverflow.com/questions/17721748/default-value-for-out-of-bounds-list-index
History
Date User Action Args
2022-04-11 14:58:58adminsetgithub: 77160
2018-03-01 18:58:05feluxesetmessages: + msg313106
2018-03-01 18:47:01rhettingersetstatus: open -> closed

nosy: + rhettinger
messages: + msg313104

resolution: rejected
stage: resolved
2018-03-01 17:09:15serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg313101
2018-03-01 16:52:09feluxecreate