Home > Software design >  Accessing nested lists with known depth variable
Accessing nested lists with known depth variable

Time:09-05

Given a nested list with a known depth n, one can access the topmost elements based on repeating the 0 index n times, for example

single_nested_list = [{'foo':['bar']}]
double_nested_list = [[{'foo':['bar']}]]

single_nested_list[0]
#returns {'foo': ['bar']}

double_nested_list[0][0]
#returns {'foo': ['bar']}

and so on...

Knowing the depth variable in advance, and assuming on the first index of each list needs to be accessed, what would be the correct syntax for accessing a nested list with n depth?

For example, if I have a triple nested list, I would need to repeat the index 3 times: [0][0][0]

triple_nested_list = [[[{'foo':['bar']}]]]

This attempt fails:

n = 3
e = [0]
triple_nested_list[[e] *  n]

Any advice on how to create an n-repeating list index would be appreciated!

CodePudding user response:

How about using straightforward recursion?

triple_nested_list = [[[1, 2, 3]]]


def get_first(alist):
    if alist and isinstance(alist, list):
        return get_first(alist[0])
    return alist


print(get_first(triple_nested_list)) # 1

CodePudding user response:

you can achieve this using a simple for loop:

>>> from operator import itemgetter
>>> def getnesteditem(n,nested_list,index = 0,/):
...    initial = triple_nested_list
...    getval = itemgetter(index)
...    for x in range(n):
...        initial = getval(initial)
...    return initial
...
>>> triple_nested_list = [[[{'foo':['bar']}]]]
>>> getnesteditem(3,triple_nested_list,0)
{'foo':['bar']}

CodePudding user response:

def levels(l):
    if not isinstance(l, list):
        yield l
    else:
        for sublist in l:
            yield from levels(sublist)

print(list(levels(l))[0]) 

Output:

{'foo':['bar']}

CodePudding user response:

Just for completion's sake, you can also use this, BUT:

  • make sure depth and index are trusted. DO NOT USE this version if they come from user input.
  • replace eval with ast.literal_eval if youhave it available.
triple_nested_list = [[[{'foo':['bar']}]]]
n = 3
e = '[0]'
statement = 'triple_nested_list' (e*n) ''
indexElement = eval(statement)
print(indexElement)
  • Related