Skip to content
Advertisement

Is there a way to find the 0th index a variable amount of times?

I don’t really have a good reason for needing to know this, but is it possible to find the 0th index a certain amount of times? Say like you have this piece of code

ar = [[[["a"]]]]
print(ar[0][0][0][0])

but instead of the 4 [0][0][0][0] you can just do like ar([0]*4). Anyway, thanks for the help.

Advertisement

Answer

What you want to do sounds weird because you will rarely run into a situation where you have an unknown nesting structure. That said, a loop is the first thing you should think of when you encounter a problem of the type “do X a bunch of times”.

For example, you could set ar to the zeroth element of ar as long as ar is an instance of type list and is also not empty.

ar = [[[["a"]]]]
while isinstance(ar, list) and len(ar) > 0:
    ar = ar[0]

print(ar) # output: a

Note: len(ar) > 0 is just for clarity if you’re a beginner. Empty lists are falsey, so you could have also just done while isinstance(ar, list) and ar:

You could also specify how many times you can drill down and the index to which you want to drill down:

def drill_down(arg, index, count):
    for i in range(count):
        if isinstance(arg, list) and len(arg) > index:
            arg = arg[index]
    return arg

ar = [[[["a"]]]]
result = drill_down(ar)
print(result) # Output: a

Or, you could use a recursive function, which can be made to behave similar to a loop:

def drill_down(arg, index, count):
    if isinstance(arg, list) and len(arg) > index and count > 0:
        return drill_down(arg[index], index, count - 1)
    return arg

ar = [[[["a"]]]]
result = drill_down(ar)
print(result) # Output: a
Advertisement