This particular iteration assigns the positive whole number to indicate the exact depth of nesting:
def generate_tree(x, index=0, depth=1):
level = x[index]
if depth < level:
index, deeper = generate_tree(x, index, depth + 1)
return index, [deeper]
so_far = [level]
index += 1
while index < len(x):
#print(level, so_far, x[index:])
this = x[index]
if this == level:
so_far.append(this)
elif this > level:
index, deeper = generate_tree(x, index, depth + 1)
so_far.append(deeper)
elif this < level:
index -=1
break
index += 1
return index, so_far
from pprint import pprint
lst = [1,2,3,4,5, 1,5, 1,2,2,3,4,1,2,3,4,1,1]
_, result = generate_tree(lst)
pprint(result, width=10)
Result
[1,
[2,
[3,
[4,
[5]]]],
1,
[[[[5]]]],
1,
[2,
2,
[3,
[4]]],
1,
[2,
[3,
[4]]],
1,
1]
Observe how the sudden shift from 1,5, places the 5 at the same nesting level as the gradual progression of 1,2,3,4,5.