Skip to content Skip to sidebar Skip to footer

How To Write A Function That Return The Value In A Nested List At The Index Path In Python?

I have to write a function that return the value at index path in the list given to us. def recursive_index(lst,index_path): if len (index_path)<1: return recursive

Solution 1:

Your function currently doesn't interact with the passed lst in any way. What it does now is to first check whether the passed index_path has more than one element. Your current test of index_path is [0], which does not have more than one element. Your function then takes the else branch and returns the first element of index_path, which is 0.

To fix this, make your function refer to lst in the appropriate places.

def recursive_index(lst,index_path):
    if index_path:
        return recursive_index(lst[index_path[0]],index_path[1:])
    else:
        return lst

If there are indices left to use, it will use the first available one to index lst, then pass that and the rest of the index_path to the function in a recursive call. When there are no more indices left, it returns whatever's left of lst.

Start a call with [1, [2], 3], [0]:

[0] is not empty, so take the first element of that and use it as an index. Pass along the rest of the indices.

[1, [2], 3][0] is 1, which we pass. The rest of the indices is [], which we pass.

[] is empty, so return the passed lst, which was 1.

>>> recursive_index([1,[2],3], [0])
1

A slightly larger test:

>>> recursive_index([1,[2, [1]], 3], [1])
[2, [1]]
>>> recursive_index([1,[2, [1]], 3], [1,0])
2
>>> recursive_index([1,[2, [1]], 3], [1,1])
[1]
>>> recursive_index([1,[2, [1]], 3], [1,1,0])
1

Post a Comment for "How To Write A Function That Return The Value In A Nested List At The Index Path In Python?"