safe usage of remove method in python

前端 未结 1 611
花落未央
花落未央 2021-01-28 03:27

I inherited a UserList class from list and implemented the following method to remove entries which are marked deleted

def purge_deleted(self):
    for element i         


        
相关标签:
1条回答
  • 2021-01-28 04:15

    You will end up skipping elements, as the iterator is not updated to allow for removed elements.

    You can iterate over the list in reverse to avoid that problem:

    def purge_deleted(self):
        for element in reversed(self):
            if ele.mark_deleted < 1:
                self.remove(element)
    

    What happens if you don't reverse is that the iterator index increments regardless of any removals; if you remove the item at index 1, the iterator moves on to item 2 even though that was item 3 before the removal (skipping the item previously at index 2).

    When you remove items in reverse however, the index moves from 1 to 0, and any removals happened 'behind' the current index. It doesn't matter anymore if item 1 was deleted or not.

    The reversed() iterator will make use of any custom __reversed__ hook, if present.

    0 讨论(0)
提交回复
热议问题