I have a function that traverses a list and prints the element whenever it is an integer as follows:
def fnc(s, d = 0, lst=[0]):
if isinstance(s, (tuple, list)):
for i, elt in enumerate(s):
if isinstance(elt, int):
# print(f'{s}, {d}, {i}, {lst}')
daccess(s, d, i, lst)
else:
lst.append(i)
fnc(elt, d+1, lst)
lst.pop(-1)
daccess
is defined as follows:
def daccess(lst, d, i, indices):
if d == 0:
print(lst[i])
else:
lst_index = lst[indices.pop(1)]
daccess(lst_index, d-1, i, indices)
fnc
is supposed to pass s, d, i, lst
as arguments to daccess
where s is the nested list(s), d is the depth of the element to access, i is its index position and lst is a trace of every nested list's index encountered. For example with (s=[1,2,[3,[4,5,6]]], d=2, i=1, lst=[0,2,1]) can be translated to s[2][1][1] == 5.
When I pass the arguments printed by fnc
on line 5 (which is commented out) to daccess
, it works as expected:
daccess(s, 0, 1, [0])
daccess(s, 0, 0, [0])
...
daccess(s, 1, 0, [0, 8])
daccess(s, 1, 1, [0, 8])
etc...
However, when calling daccess
inside fnc
(so just calling fnc(s) I get this error:
1
2
33
6425
64
Traceback (most recent call last):
File "fa.py", line 56, in <module>
fnc(s)
File "fa.py", line 20, in fnc
fnc(elt, d+1, lst)
File "fa.py", line 17, in fnc
daccess(s, d, i, lst)
File "fa.py", line 8, in daccess
lst_index = lst[indices.pop(1)]
IndexError: pop index out of range
s is defined as follows: s = ( 1, 2, 33,6425, ( 3, 4, 44, ( 5, 66, 63225, 25673547, 88 ), ( 64,121 ) ), 9, 10, 11, ( 89, 90 ) )
(I know this is a tuple of tuples but just assume it's a list of lists. I have a separate function to convert a tuple of tuples to a list of lists before calling anything else)
I tried using a deep copy of s
and indices
but i get the same error back. I know for sure that if i call just daccess
in the main file with the correct arguments it works but I really don't know what goes wrong when calling it inside fnc
.
Any help as to why this happens is appreciated.