For循环不会遍历所有对象

gho*_*der 1 python for-loop list

为什么这个for循环不能遍历所有项目:

 temp = 0

 for br in my_list :
    temp +=1
    #other code here
    #my list is not used at all, only br is used inside here
    my_list.remove(br)

 print temp
 assert len(my_list) == 0 , "list should be empty"
Run Code Online (Sandbox Code Playgroud)

因此,断言开火了.然后我添加了临时计数器,我确实看到尽管我的列表有202个元素,但for循环只处理了101个元素.这是为什么?

Atr*_*ors 5

您不应该从正在迭代的列表中删除.如果你想删除东西,请使用此选项

while list:
   item = list.pop()
   #Do stuff
Run Code Online (Sandbox Code Playgroud)

编辑:如果您想了解更多关于pop()在外观蟒蛇DOC

如果订单很重要,请使用pop(0).pop()默认情况下删除最后一项,如果您想按顺序浏览列表,则应pop(0)删除第一个(索引0)项并返回它.

Edit2:感谢用户Vincentwhile list建议.