Removing from a list while iterating over it

后端 未结 4 1649
走了就别回头了
走了就别回头了 2020-11-22 03:05

The following code:

a = list(range(10))
remove = False
for b in a:
    if remove:
        a.remove(b)
    remove = not remove
print(a)

Outp

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 03:45

    On your first iteration, you're not removing and everything's dandy.

    Second iteration you're at position [1] of the sequence, and you remove '1'. The iterator then takes you to position [2] in the sequence, which is now '3', so '2' gets skipped over (as '2' is now at position [1] because of the removal). Of course '3' doesn't get removed, so you go on to position [3] in the sequence, which is now '4'. That gets removed, taking you to position [5] which is now '6', and so on.

    The fact that you're removing things means that a position gets skipped over every time you perform a removal.

提交回复
热议问题