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

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

    Python doesn't support altering the length of a list while you iterate over it. Work on a copy or use a list comprehension instead.

    Think about how Python is actually doing the for loop - it counts up through the elements, returning the item at the current index. When you remove one, the index means a different element.

提交回复
热议问题