blend_smile
blend_smile

Reputation: 3

How to access an element of a nested list with loop

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)

Upvotes: 0

Views: 195

Answers (2)

SomeDude
SomeDude

Reputation: 14228

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.

Upvotes: 2

martineau
martineau

Reputation: 123393

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

Upvotes: 0

Related Questions