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

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

    You could use a while loop rather than a for loop for this task.

    while len(some_list)>0 :
        some_list.pop(0)
    

    A for loop will actually iterate over each item in the list, which will not work as the indices in the list will change with each deletion, and you will not end up getting all items.

    However, a while loop will check a condition every time the loop is run, and if it is still true, run the code again. Here we specify that the length of the list has to be more than 0, i.e. there has to be content in the list.

提交回复
热议问题