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

Paul Moore p.f.moore at gmail.com
Sun Mar 5 06:27:07 EST 2017


On 3 March 2017 at 18:29, Ed Kellett <edk141 at gmail.com> wrote:
> I guess I don't have any hope of convincing people who think there's no need
> to ever do this, but I have a couple of questions for the people who think
> the existing solutions are fine:
>
> - Which of the existing things (slice + [default], conditional on a slice,
> conditional on a len() call) do you think is the obvious way to do it?

Write a small wrapper function that implements the functionality
(however you want, but it doesn't have to be a single expression, so
you've much more flexibility to make it readable) and then use that.

> - Are there any examples where list.get would be applicable and not the
> obviously best way to do it?

I don't understand the question. If you're asking which is better
between list.get and a custom written function as described above,
then a custom written function is better because (a) it works on all
Python versions, (b) list.get needs a language change where a helper
function doesn't, (c) "writing a helper function" is a generally
useful idiom that works for many, many things, but list.get only
solves a single problem and every other such problem would need its
own separate language change. The disadvantage that you have to write
the helper is trivial, because it's only a few lines of simple code:

def get_listitem(lst, n, default=None):
    try:
        return lst[n]
    except IndexError:
        return default

Paul


More information about the Python-ideas mailing list