0

I have to do a code where I have to change some value in a for loop. I have a list called listElement. I know the exact position of the item that I want to change which is store in a list. For instance [2,2,1] called index (which can also be for instance [3,2] because my listElement is composed of several lists of different sizes).

I would like to do something like this :listElement + index which can create something like listElement[2][2][1] (or listElement[3][2])

listElement = [ "a" , ["b","c"] , [["d"],["e","f"]] ]

tab = [ [2,1,0] , [0] ] # "e" and "a" position

element=""
for i in tab :
    # recuperate the element at the position indicate by i

    element = listElement[i]
1
  • 1
    Can you show us what you have tried so far, please? Commented Aug 20, 2020 at 10:50

3 Answers 3

2

You could do something like the following:

def recursiveAccess(list, elem):
    if len(elem) == 1:
        return list[elem[0]]
    return recursiveAccess(list[elem[0]], elem[1:])

listElement = [ "a" , ["b","c"] , [["d"],["e","f"]] ]

tab = [ [2,1,0] , [0] ] # "e" and "a" position

for e in tab:
    print(recursiveAccess(listElement, e))
# e
# a

Due to the fact you don't know in advance the access tree to an element of the list a recursive solution is in place. Notice that you should add some checks to validate that the input are always valid.

Sign up to request clarification or add additional context in comments.

Comments

2

Subclass ListElement from list and define method __add__:

class ListElement(list):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


    def __add__(self, l):
        if not isinstance(l, (list, tuple)):
            raise ValueError('value must be a list or tuple')
        the_list = self
        for inx in l:
            if not isinstance(inx, int):
                raise ValueError('the indices must be ints')
            the_list = the_list.__getitem__(inx)
        return the_list

listElement = ListElement([5, 6, [1, 2], [8, 9, [3, 8, 1]]])
print(listElement + [3, 2])

Prints:

[3, 8, 1]

Comments

1

You can just iterate on each index in the indices-list and get the next level each time:

def get_list_element(lst, indices):
    element = lst
    for index in indices:
        element = element[index]
    return element

The following program:

lst = [ "a", ["b", "c"], [["d"], ["e", "f"]] ]
indices_list = [[2,1,0] , [1], []]
for indices in indices_list:
    print(get_list_element(lst, indices))

Will output:

e
['b', 'c']
['a', ['b', 'c'], [['d'], ['e', 'f']]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.