I’m working with an instance of nltk.tree.ParentedTree, but I think the question is more general than that.
Basically, I have a list of arbitrarily deep nesting, and I want to delete part of the list (though I don’t know how deeply nested that part is). I have a search function that finds an occurrence of an item in the list, which returns a tuple of n integers, where n is the depth of the element that was found.
For example, say I have l = [[['cat', 'dog']], ['fish']] When I call search(l, 'dog') it returns (0, 0, 1). This is telling me that l[0][0][1] == 'dog'. If I knew that 'dog' occurred at (0, 0, 1) ahead of time, I could delete it from the list just by doing del l[0][0][1]. But I don’t know that ahead of time so I need to programmatically do the same kind of thing.
I can access the element 'dog' in the list by doing
indices = search(l, 'dog')
for i in indices:
l = l[i]
So now l is 'dog'. But, I’m not sure how to get from there to deleting it from the list. I don’t just want to set it to None.
You can loop over all but the last of the references and then use the last one to delete the item:
By using all but the last index you resolved the reference to the parent of the referenced item, so now you can delete it with the last index.