With python’s dictionary objects, you have the useful get method:
>>> d = {'a':1, 'b':2, 'c':3}
>>> d.get('a')
1
>>> d.get('d', 'not found')
'not found'
Sometimes, I find something like this would be useful for lists, using the list’s index in place of the dict’s key:
>>> l = [0,1,2,3]
>>> l.get(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'get'
Here’s a quick lambda that accomplishes that:
list_get = lambda l,i,a=False: (len(l) <= i and a) or (len(l) > i and l[i])
Usage:
>>> list_get = lambda l,i,a=False: (len(l) <= i and a) or (len(l) > i and l[i])
>>> my_list = [0,False,None,3]
>>> list_get(my_list,0)
0
>>> list_get(my_list,1)
False
>>> list_get(my_list,2) # returns None
>>> list_get(my_list,3)
3
>>> list_get(my_list,4)
False
>>> list_get(my_list,4,0) # Note: returns False instead of 0
False
>>> list_get(my_list,4,1)
1
It’s not perfect. Be careful with False-equivalent values in the alt parameters as noted above. But otherwise it should work for most practical cases were such usage is desired.