Why does a for-loop with pop-method (or del statement) not iterate over all list elements

前端 未结 5 1821
长情又很酷
长情又很酷 2020-12-11 03:46

I am new to Python and experimenting with lists I am using Python 3.2.3 (default, Oct 19 2012, 20:13:42), [GCC 4.6.3] on linux2

Here is my samplecode



        
5条回答
  •  北海茫月
    2020-12-11 04:40

    Unrolling a bit (the caret (^) is at the loop "index"):

    your_list = [1,2,3,4,5,6]
                 ^
    

    after popping off the first item:

    your_list = [2,3,4,5,6]
                 ^
    

    now continue the loop:

    your_list = [2,3,4,5,6]
                   ^
    

    Now pop off the first item:

    your_list = [3,4,5,6]
                   ^
    

    Now continue the loop:

    your_list = [3,4,5,6]
                     ^
    

    Now pop off first item:

    your_list = [4,5,6]
                     ^
    

    Now continue the loop -- Wait, we're done. :-)


    >>> l = [1,2,3,4,5,6]
    >>> for x in l:
    ...     l.pop(0)
    ... 
    1
    2
    3
    >>> print l
    [4, 5, 6]
    

提交回复
热议问题