user3692467
user3692467

Reputation: 33

Python2: access nested list using a list of indices

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!

Upvotes: 1

Views: 62

Answers (1)

Adam Smith
Adam Smith

Reputation: 54163

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)

Upvotes: 3

Related Questions