Modifying a list while iterating over it - why not?

前端 未结 4 1832
一个人的身影
一个人的身影 2020-11-30 14:39

Almost every tutorial and SO answer on this topic insists that you should never modify a list while iterating over it, but I can\'t see why this is such a bad thing if the c

4条回答
  •  春和景丽
    2020-11-30 15:00

    while len(mylist) > 0:
        print mylist.pop()
    

    You are not iterating over the list. You are each time checking an atomic condition.

    Also:

    while len(mylist) > 0:
    

    can be rewritten as:

    while len(mylist):
    

    which can be rewritten as:

    while mylist:
    

提交回复
热议问题