Q:

Way to insert elements into list at variable depth?

How do I insert an element into a program-specified level of a list? My solution isn't very Pythonic:
def listInsertDepth(l,e,i,lvl): # Insert element e into list l at depth lvl using list of indices i
    if lvl < 0: # That is, if your depth level is invalid
        return l
    else:
        assert len(i) == lvl+1 # One index for every level, plus for the actual insertion
        s = l # A copy for tampering with
        for index in range(lvl):
            s = s[i[index]]
        s.insert(i[-1],e)
        return listInsertDepth(l,s,i[:-1],lvl-1) 

A:

Given a series of indices, you can simply loop over them all except for the last one to traverse your nested structure to the parent list to insert into:
listInsertAtDepth(lst, value, indices):
    parent = lst
    for index in indices[:-1]:
        parent = parent[index]
    parent.insert(indices[-1], value)

You can add a try, except combo to detect that you got your index wrong:
listInsertAtDepth(lst, value, indices):
    parent = lst
    try:
        for index in indices[:-1]:
            parent = parent[index]
        parent.insert(indices[-1], value)
     except IndexError:
        return None

but personally, I'd rather get an exception than having it swallowed and discarded like that.
Note that you should not return lst from your function, as it is altered in-place. Python stdlib methods like .append() and .extend(), that modify a list in-place don't return anything either.

