Python: Adding element to list while iterating

前端 未结 11 637
太阳男子
太阳男子 2020-12-02 15:37

I know that it is not allowed to remove elements while iterating a list, but is it allowed to add elements to a python list while iterating. Here is an example:



        
11条回答
  •  一生所求
    2020-12-02 15:52

    well, according to http://docs.python.org/tutorial/controlflow.html

    It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.

提交回复
热议问题