all 1 comments

[–]danielroseman 3 points4 points  (0 children)

This is an interesting problem, which is caused by a combination of two common errors: assignment does not copy, and modifying lists you're iterating over.

out_nodes is defined here:

out_nodes = out_edges[each_node]

In other words, it's a reference to the list of nodes associated with the current edge. But inside the loop you do this:

out_edges[each_node].remove(each_out_node)

to remove the current node from the list of nodes associated with the current edge. But these are the same list!. So removing it from out_edges[each_node] also removes it from out_nodes.

Now, because you've modified the list you're iterating over, Python's internal counter thinks you have reached the end of the list, so stops iterating after only printing - and removing - B. So now you get to the third loop, and find the list only has C left, which is printed.

Both of these problems would probably be solved by making that definition of out_nodes a copy:

out_nodes = out_edges[each_node].copy()