iterators and continuing after a StopIteration

Roald de Vries downaold at
Sat Aug 7 15:57:00 CEST 2010

Hi all,

I have a list that I'm iterating over, and during the iteration items  
are appended. Moreover, it is iterated over in two nested loops. If  
the inner loop comes to the end, I want the outer loop to append an  
item. Is there a way to do this? Because once an iterator has raised a  
StopIteration, it can not go to a next item anymore.

Aside question: is there a rationale for the current behavior? To me  
it seems more natural to continue iteration after appending new items.

I want to use it for a graph walk.

nodes is a list of all nodes,
edges is an on the fly constructed list of edges in the order of  
initial_nodes is a list of (root) nodes

     edges = []
     edge_it = iter(edges)
     for node in initial_nodes:
         edges += node.leaving_edges
             while True:
                 edge =
                 edges += edge.head.leaving_edges
         except StopIteration:

Thanks in advance, cheers, Roald

More information about the Python-list mailing list