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

Steven D'Aprano steve at pearwood.info
Tue Feb 28 09:45:19 EST 2017

On Tue, Feb 28, 2017 at 12:54:26PM +0100, Michel Desmoulin wrote:
> dict.get() is a very useful method, but for lists and tuples, we need to
> rely on try/except instead.

No you don't. You can use slicing.

alist = [1, 2, 3]
print(alist[99:100])  # get the item at position 99

In my experience, dict.get is very useful, but list.get only *seems* 
useful. I've written my own version:

def get(alist, pos, default=None):
        return alist[pos]
    except IndexError:
        return default

but then struggled to find a good use for it. It seems like it ought to 
be useful, but in practice I found that it was only covering up bugs in 
my code. If I was indexing a list outside of the range of existing 
items, that's a bug, and using get() just made it hard to fix.

> Can we get list.get and tuple.get as well?
> Also, for list, a list.setdefault like the dict.setdefault would be logical.

What would it do?

For example, given:

alist = []
y = alist.setdefault(10, 'a')

what will alist equal?


More information about the Python-ideas mailing list