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)
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:
You can add a
try,exceptcombo to detect that you got your index wrong:but personally, I’d rather get an exception than having it swallowed and discarded like that.
Note that you should not return
lstfrom 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.