Python: Adding element to list while iterating

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

Leave a Comment