Python: Adding element to list while iterating

前端 未结 11 664
太阳男子
太阳男子 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:45

    make copy of your original list, iterate over it, see the modified code below

    for a in myarr[:]:
          if somecond(a):
              myarr.append(newObj())
    

提交回复
热议问题