For loop iterates less times than I expected in Python

后端 未结 3 697
春和景丽
春和景丽 2020-12-21 04:01

I would expect the following loop to iterate six times, instead it iterates three with python3. I don\'t understand this behavior. I understand that the list changes as I d

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-21 04:36

    You are deleting the first element in every iteration of the loop by del a[0], so the iterator is emptied in 3 steps, because it moves to the element after the one you removed on the next iteration. You can check the element the iterator is currently on, and the list status in the code below

    a = [1, 2, 3, 4, 5, 6]
    for elem in a:
        print(elem)
        del a[0]
        print(a)
    

    The output is

    1
    [2, 3, 4, 5, 6]
    3
    [3, 4, 5, 6]
    5
    [4, 5, 6]
    

    You can think of it as a pointer pointing to the first element of the list, that pointer jumps 2 steps when you delete the first element on each iteration, and it can jump only 3 times for 6 elements.

    Generally it is a bad idea to modify the same list you are iterating on. But if you really want to, you can iterate over the copy of the list a[:] if you really want to delete items

    a = [1, 2, 3, 4, 5, 6]
    for elem in a[:]:
        del a[0]
        print(a)
    

    The output is

    [2, 3, 4, 5, 6]
    [3, 4, 5, 6]
    [4, 5, 6]
    [5, 6]
    [6]
    []
    

提交回复
热议问题