yoyo
yoyo

Reputation: 69

extracting a value from a nested list using a specific index

so i basically have a nested list that will be constantly changing but for example it will look like this:

[9,1,[3,5][3]] 

and then I'm also getting a generated index that's formatted like this:

[2,1] 

so, at index [2,1] the value is '5' but how do I write code that will automatically extract this value for me? the list will be constantly changing and the indexes will also be changing (will always be a valid index) so I cant just used a nested for loop. is there any easy way to do this?

Upvotes: 3

Views: 1246

Answers (3)

XMehdi01
XMehdi01

Reputation: 1

Make a copy of L to c and loop over indices and In each loop you will get one level deeper until you reach the final value.

L = [9,1,[3,5],[3]]
indices = [2,1]
c = L.copy()
for i in indices:
    c = c[i]
print(c) #5

Upvotes: 0

Parzival
Parzival

Reputation: 57

If your index isn't changing in dimension, maybe you could just use the hard-coded value? If they are changing, you can iterate with your indexes and pop the items, until you reach your item index.

lst = [9, 1, [3, 5], [3]]
idx = [2, 1]

print(lst[idx[0]][idx[1]])

// or 
for i in idx:
    lst = lst.pop(i)

Upvotes: 1

blackraven
blackraven

Reputation: 5597

You could iterate through the required index, and use <list>.pop(<index>) to extract the element using its index.

L = [9,1,[3,5],[3]]
idx = [2,1]

for i in idx:
    L = L.pop(i)
print(L)

Output

5

Upvotes: 2

Related Questions