Python: Adding element to list while iterating

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

    You can use an index and a while loop instead of a for loop if you want the loop to also loop over the elements that is added to the list during the loop:

    i = 0
    while i < len(myarr):
        a = myarr[i];
        i = i + 1;
        if somecond(a):
            myarr.append(newObj())
    

提交回复
热议问题