1

how do I access an element of a nested list with another list which contains the indices?

e.g:

# this is the variable containing the indices
a = [0, 1]

b = [[1,2],[3,4]]

in reality, these lists are filled with elements of self defined classes and the list containing the "coordinates" (a) has more than 2 elements.

Is there any possibility to access b[0][1] automatically? Previously, I used this code:

c = deepcopy(b)
for el in a:
    c = c[el]

but since b is pretty big, I'd love to get rid of that deepcopy without manipulating b in reality.

I am happy about any suggestions :)

Thanks!

4
  • 5
    I sense an XY Problem. Commented May 27, 2015 at 16:35
  • What's your goal with this code? Commented May 27, 2015 at 16:37
  • I have a nested list b, whose elements i would like to acces using the indices in the list a. The second code fragment just shows what I've used so far. If you have any suggestions, please tell me :) Commented May 27, 2015 at 16:45
  • Really, the correct way to do it is b[a[0]][a[1]] there is no pretty way to do it. Commented May 27, 2015 at 17:03

1 Answer 1

3

Just toss it in a function. That will keep it scoped so you don't overwrite the original value

def nested_getitem(container, idxs):
    haystack = container
    for idx in idxs:
        haystack = haystack[idx]
    return haystack

DEMO:

>>> a = [0, 1]
>>> b = [[1, 2], [3, 4]]
>>> nested_getitem(b, a)
2

You could probably do this with a functools.reduce as well, if you were insane.

import functools
import operator

def nested_getitem(container, idxs):
    return functools.reduce(operator.getitem, idxs, container)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This works for giving out the elements, but what if i wanted to manipulate the item? e.g. nested_getitem(b,a) = 0.
@user3692467 in which case why are you trying to deepcopy in the example in your question???

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.