0

how to access an element of nested list with a loop? like:

a = [20,[22,[3,[21],3], 30]]
               #^^ i want to access this

how to access it with a loop, insead of using

a[1][1][1][1]

any solution on any language is accepted (preferably python)

5
  • Are you trying to iterate to see all of the items in the nested list, or just a specific item? Commented May 5, 2021 at 2:10
  • @Axiumin_ just one specific item Commented May 5, 2021 at 2:11
  • Do you want this to be dynamic or will the lists of lists be one element each? Commented May 5, 2021 at 2:11
  • @12944qwerty i want this to be dynamic Commented May 5, 2021 at 2:12
  • 2
    I think recursion is the best way (instead of a loop). See SomeDude's answer down Commented May 5, 2021 at 2:14

2 Answers 2

2

Are you looking for something like:

def get_inner_most(a):
  if not isinstance(a, list):
    return a
  elif len(a) == 0:
    return None
  elif len(a) == 1:
    return a[0]
  return get_inner_most(a[1])

You need to note that it will get you only the first inner most element found and I hope that is your requirement. For example for the input [20,[22,[3,[21],3], 30], [9,[4,[5,[6]]]]] it will still return 21 but not 6. If that is your requirement i.e. the element at the largest depth then you need to update your question.

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

Comments

0

It's not via an explicit loop, but you can use the functoools.reduce() function as illustrated below:

from functools import reduce

def nested_getter(lst, *args):
    return reduce(lambda s, i: s[i], args, lst)


a = [20,[22,[3,[21]]]]
print(nested_getter(a, 1, 1, 1, 0))  # -> 21

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.