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

前端 未结 5 1843
长情又很酷
长情又很酷 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:21

    You have to be careful when attempting to modify collections you are iterating over. In this case, the list keeps track of the "current position" with a simple integer index. When you use pop(), everything changes index, and so elements are skipped.

    On the first iteration of the loop, i is l[0]. Then you pop the list, then you access l[1], which is what originally was at l[2]. Then you pop the list, and the next iteration accesses l[2], which is what used to be at l[4], etc.

    There's no need to pop elements in this code anyway, presumably you are doing something more complex in your real code.

提交回复
热议问题