python列表元素的删除

#今天看到有人说列表删除元素会碰到index out of range的问题:

lst = [0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 0, 44, 1, 0]
for i in range(len(lst)):
    if(lst[i] == 0):
        del lst[i]
#list index out of range
感觉原因是:在你每次删除一个元素那么后面的会补足前面被删掉的,那么就像c++中链表一样这样从前向后删是不行的,从后往前删就不存在这种情况,如下:
lst = [0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 0, 44, 1, 0]
for i in reversed(range(len(lst))):
    if(lst[i] == 0):
        del lst[i]
    print(i, end=":")
    print(lst)
#下面是输出结果    
21:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 0, 44, 1]
20:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 0, 44, 1]
19:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 0, 44, 1]
18:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 44, 1]
17:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 44, 1]
16:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 44, 1]
15:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 1, 44, 1]
14:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 44, 1]
13:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 44, 1]
12:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 1, 2, 1, 44, 1]
11:[0, 1, 2, 2, 2, 1, 0, 0, 0, 0, 0, 1, 2, 1, 44, 1]
10:[0, 1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