3

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?

2
  • just loop over the generated index and grab the element from the nested list that matches the current index in the loop Commented Jun 6, 2021 at 4:17
  • [3,5][3] isn't valid. You meant [3,5], [3], right? Commented Oct 3, 2023 at 16:32

3 Answers 3

2

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

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

Comments

1

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)

Comments

0

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

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.