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

Michel Desmoulin desmoulinmichel at gmail.com
Tue Feb 28 10:16:28 EST 2017

Le 28/02/2017 à 15:45, Steven D'Aprano a écrit :
> 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

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.

It's a very different use case.

> 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):
>     try:
>         return alist[pos]
>     except IndexError:
>         return default

Based on your rational, we would just reject dict.get as well the first
time it's implemented.

> 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. 

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

Plus it's consistent. It's only fair to expect it to exists after you
learn about dict.get.

First places where I missed it at the top of my head was *args, sys.argv

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?

Fair enough.

More information about the Python-ideas mailing list