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 ... >>> get("abc", -1, "default") 'c' -- https://mail.python.org/mailman/listinfo/python-list