safe usage of remove method in python

浪子不回头ぞ 提交于 2019-12-02 10:04:59

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!