How to simultaneously iterate and modify list, set, etc?

前端 未结 3 1398
抹茶落季
抹茶落季 2020-12-22 08:46

In my program I have many lines where I need to both iterate over a something and modify it in that same for loop.

How

3条回答
  •  余生分开走
    2020-12-22 08:59

    This is a conceptual misunderstanding.

    It is dangerous to modify the list itself from within the iteration, because of the way Python translates the loop to lower level code. This can cause unexpected side effects during the iteration, there's a good example here :

    https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/

    But modifying mutable objects stored in the list is acceptable, and common practice.

    I suspect that you're thinking that because the list is made up of those objects, that modifying those objects modifies the list. This is understandable - it's just not how it's normally thought of. If it helps, consider that the list only really contains references to those objects. When you modify the objects within the loop - you are merely using the list to modify the objects, not modifying the list itself.

    What you should not do is add or remove items from the list during the iteration.

提交回复
热议问题