0

I am not understanding the behavior that Python is giving me in the following:

>>> adj = gx.g.neighbors('v') >>> adj ['x', 'w'] >>> gx.d['x'] [13, 14, 'black', 'v'] >>> gx.d['w'] [9, 333, 'black', 'v'] >>> for x in adj: #for every element in the list ... print "x", x, gx.d[x] ... print "color", gx.d[x][2] ... if gx.d[x][2] != 'white': ... adj.remove(x) ... x x [13, 14, 'black', 'v'] color black >>> adj ['w'] 

What I do not understand is why it appears that only the element 'x' gets printed in the loop. What happened to 'w'. The output of the algorithm segment should be an empty list as both elements of adj are black.

4
  • 3
    You're iterating over a list and removing elements from it at the same time. That's not a good idea. Commented Apr 4, 2013 at 3:12
  • I think I have done this in Java before? Is there a difference in the static/dynamic nature of each language? Commented Apr 4, 2013 at 3:14
  • 1
    It's a bad idea to do that in both languages. Commented Apr 4, 2013 at 3:16
  • The reason why you shouldn't iterate over a list and remove elements at the same time is because you don't have control over the iteration code. It expects that the list remains in tact as it is going over it. You may get it to work sometimes, but it is always considered bad practice, difficult to read, difficult to reason about, and dangerous. Commented Apr 4, 2013 at 3:20

1 Answer 1

4

Instead of removing elements, make a new list:

new_adj = [x for x in adj if gx.d[x][2] == 'white'] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.