On 3/31/2016 11:24 AM, Peter Otten wrote:
Steven D'Aprano wrote:

Sometimes people look for a method which is equivalent to dict.get, where
they can set a default value for when the key isn't found:


py> d = {1: 'a', 2: 'b'}
py> d.get(999, '?')
'?'


The equivalent for sequences such as lists and tuples is a slice. If the
slice is out of range, Python returns a empty sequence:

py> L = [2, 4, 8, 16]
py> L[5]  # out of range, raises IndexError
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
IndexError: list index out of range
py> L[5:6]  # out of range slice return empty list
[]

To get a default:

py> L[5:6] or -1
-1


This is short and simple enough to use in place, but we can also wrap this
into a convenient helper function:

def get(seq, index, default=None):
     return (seq[index:index+1] or [default])[0]



py> get(L, 2, -1)
8
py> get(L, 200, -1)
-1

But note:

def get(seq, index, default=None):
...     return (seq[index:index+1] or [default])[0]
...
get("abc", -1, "default")
'default'

God old try...except to the rescue:

def get(seq, index, default=None):
...     try: return seq[index]
...     except IndexError: return default

Replace IndexError with (IndexError, KeyError) and the functions works with any subscriptable that raises either exception.

...
get("abc", -1, "default")
'c'




--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to