kosta5
kosta5

Reputation: 1138

How to remove an element from a list while traversing it?

I've done my reading trust me. And python still acts up when removing an item from the list. I have a graph implementation.

Now there is this one function that is supposed to delete some edges that the node has attached. I have a list of Edge objects and want to remove them by value...

Code is something like this:

for edge in node.edgeList:
...
   edgeToRemove = edge # edgeToRemove now holds something like <edge.Edge object at 0x107dcaf90>
   node.edgeList.remove(edgeToRemove) #KINDA WORKS - just doesnt behave consistently...It removes some edges but not others

What is the best way to remove them?

Upvotes: 1

Views: 4645

Answers (3)

user130076
user130076

Reputation:

You could use lit comprehension - although your problem may be in your __eq__/__ne__ methods for edges (you should post that). Try this, though:

node.edgeList = [edge for edge in node.edgeList if edge != edgeToRemove]

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799430

Get the index of the element and del it.

del somelist[n]

Upvotes: 1

senderle
senderle

Reputation: 151157

Don't change the length of a list while iterating over it. It won't work.

>>> l = range(10)
>>> for i in l:
...     l.remove(i)
... 
>>> l
[1, 3, 5, 7, 9]

See? The problem is that when you remove an item, the following items are all shifted back by one, but the location of the index remains the same. The effect is that the item after the removed item gets skipped. Depending on what you're doing, a list comprehension is preferable.

>>> l = range(10)
>>> for i in l:
...     if i in [2, 3, 5, 6, 8, 9]:
...         l.remove(i)
... 
>>> l
[0, 1, 3, 4, 6, 7, 9]
>>> [i for i in range(10) if not i in [2, 3, 5, 6, 8, 9]]
[0, 1, 4, 7]

Upvotes: 6

Related Questions