Search code examples
pythonlistnestedindices

Change elements of list based on list of indices


How can a list of indices (called "indlst"), such as [[1,0], [3,1,2]] which corresponds to elements [1][0] and [3][1][2] of a given list (called "lst"), be used to CHANGE their respective elements in the original list? Also note that the indices refer to elements which are nested to an arbitrary depth. For example, given

indlst = [[1,0], [3,1,2]]
lst = ["a", ["b","c"], "d", ["e", ["f", "g", "h"]]]
required_output = [lst[1][0],lst[3][1][2]]

The output should correspond to ["b","h"]. I know I can get this far with the following snippet (see Use list of nested indices to access list element):

for i in indlst:
    temp = lst
    for j in i:
        temp = temp[j]
    print(temp)
b
h

However, I need to CHANGE these elements within the the original list. For example, changing each of the accessed elements to "CHANGED":

changed_lst = ["a", ["CHANGED","c"], "d", ["e", ["f", "g", "CHANGED"]]]

Solution

  • Just check for the innermost index in each sequence - when you reach it, change the value, instead of going deeper in the sequence and just retriveing the element:

    for indices in indlst:
        base = lst
        for i, index in enumerate(indices):
            if i == len(indices) - 1:
                base[index] = "CHANGED"
                break
            base = base[index]
    

    This alternate form might be more elegant, alhtough it is just the samething:

    for indices in indlst:
        base = lst
        for index in indices[:-1]: 
            base = base[index]
        base[indices[-1]] = "CHANGED"