Python: Adding element to list while iterating

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

    Why don't you just do it the idiomatic C way? This ought to be bullet-proof, but it won't be fast. I'm pretty sure indexing into a list in Python walks the linked list, so this is a "Shlemiel the Painter" algorithm. But I tend not to worry about optimization until it becomes clear that a particular section of code is really a problem. First make it work; then worry about making it fast, if necessary.

    If you want to iterate over all the elements:

    i = 0  
    while i < len(some_list):  
      more_elements = do_something_with(some_list[i])  
      some_list.extend(more_elements)  
      i += 1  
    

    If you only want to iterate over the elements that were originally in the list:

    i = 0  
    original_len = len(some_list)  
    while i < original_len:  
      more_elements = do_something_with(some_list[i])  
      some_list.extend(more_elements)  
      i += 1
    

提交回复
热议问题