Deleting layers not working if objects moved to another layer before

Hi all,

here is a script to flatten all child layers so that no more nested layers are present.
Everything works well except that scriptcontext.doc.ActiveDoc.Layers.Delete(lay.Id,True) does nothing if a object is moved to another layer before.

I guess i miss something simple maybe commit changes to the layer.Table…dont know.
I descriped the problem in big letters on the line wehre nothing happens.

import scriptcontext as sc

act_doc = sc.doc.ActiveDoc

# iterate over layers
for lay in act_doc.Layers:
    # get all child layers
    if len(str(lay).split('::')) > 1:
        # check if objects on this layer
        if len(act_doc.Objects.FindByLayer(lay)) > 0:
            # move objects to the first parent layer
            for obj in act_doc.Objects.FindByLayer(lay):
                lay_first = act_doc.Layers.FindName(str(lay).split('::')[0])
                obj.Attributes.LayerIndex = lay_first.LayerIndex
                obj.CommitChanges()
            # delete the child layer
            # HERE IS THE PROBLEM THE LAYER WILL NOT BE DELETED
            # ONLY IF THE SCRIPT RUN A SECOND TIME
            # BUT THAN ITS THE ELSE STATEMENT
            act_doc.Layers.Delete(lay.Id,True)
            
        else:
            act_doc.Layers.Delete(lay.Id,True)

Maybe someone had the same issue and a solution for it.
Thanks in advanced

I guess the problem is if a layer have a child layer and the child layer have a object this parent layer cant be deleted before the child layer object is moved to another layer.
So the solution is is to move first all objects to the first layer and delete afterwards all empty child layers.
This means a second loop.

import scriptcontext as sc

act_doc = sc.doc.ActiveDoc

# iterate over layers
for lay in act_doc.Layers:
    # get all child layers
    if len(str(lay).split('::')) > 1:
        # check if objects on this layer
        if len(act_doc.Objects.FindByLayer(lay)) > 0:
            # move objects to the first parent layer
            for obj in act_doc.Objects.FindByLayer(lay):
                lay_first = act_doc.Layers.FindName(str(lay).split('::')[0])
                obj.Attributes.LayerIndex = lay_first.LayerIndex
                obj.CommitChanges()

act_doc.Views.RedrawEnabled = False
for lay in act_doc.Layers:
    # get all child layers
    if len(str(lay).split('::')) > 1:
        # delete all child layers
        act_doc.Layers.Delete(lay.Id,True)