Python: Adding element to list while iterating

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

    You could use the islice from itertools to create an iterator over a smaller portion of the list. Then you can append entries to the list without impacting the items you're iterating over:

    islice(myarr, 0, len(myarr)-1)
    

    Even better, you don't even have to iterate over all the elements. You can increment a step size.

提交回复
热议问题