Movatterモバイル変換


[0]ホーム

URL:


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

Steven D'Apranosteve 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 99In 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 defaultbut 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?-- Steve


More information about the Python-ideasmailing list

[8]ページ先頭

©2009-2026 Movatter.jp