python - Why doesn't list have safe "get" method like dictionary? -


>>> d = {'a':'b'} >>> d['a'] 'b' >>> d['c'] keyerror: 'c' >>> d.get('c', 'fail') 'fail'  >>> l = [1] >>> l[10] indexerror: list index out of range 

ultimately doesn't have safe .get method because dict associative collection (values associated names) inefficient check if key present (and return value) without throwing exception, while super trivial avoid exceptions accessing list elements (as len method fast). .get method allows query value associated name, not directly access 37th item in dictionary (which more you're asking of list).

of course, can implement yourself:

def safe_list_get (l, idx, default):   try:     return l[idx]   except indexerror:     return default 

you monkeypatch onto __builtins__.list constructor in __main__, less pervasive change since code doesn't use it. if wanted use lists created own code subclass list , add get method.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -