Slice equivalent to dict.get
Steven D'Aprano
steve at pearwood.info
Thu Mar 31 11:07:02 EDT 2016
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
--
Steven
More information about the Python-list
mailing list