I have a complex multidimensional utterable object (say, list). I want to write function to access the value of an element represented by tuple of indices. The number of dimensions is itself variable. It should also return None
if the element does not exist:
l = [[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]]
access(l, (0, 0, 0)) # prints 1
access(l, (0, 1, 1)) # prints 4
access(l, (1, 1)) # prints [7, 8]
access(l, (0, 1, 2)) # prints None
access(l, (0, 0, 0, 0)) # prints None
How do I achieve this?
You can do it using reduce()
:
def access(obj, indexes):
return reduce(lambda subobj, index: subobj[index] if isinstance(subobj, list) and index < len(subobj) else None, indexes, obj)
Or as pointed by @chepner, you can use def
to make it more readable:
def access(obj, indexes):
def _get_item(subobj, index):
if isinstance(subobj, list) and index < len(subobj):
return subobj[index]
return None
return reduce(_get_item, indexes, obj)