Reputation: 11774
So I'm iterating over items in a list in this way:
for virus in viruses:
do stuff
remove virus
If I had the index, I could just do del virus[i], and I could obviously tweak the code to do something like for index in range(0, len(viruses))
, but that starts to make the code ugly pretty quickly for the other things I want to do within the for loop. Is there anyway I can just remove based on the name of the virus I am currently iterating over?
Upvotes: 4
Views: 12590
Reputation: 387
Although one of your options is to use remove()
, that may return an error. Another option is to treat viruses (which is assumed to be a list) as a stack (or a queue)
for _ in xrange(len(viruses)):
virus = viruses.pop()
# do stuff with virus
If viruses
is instead a dictionary (and virus
the key), then the key is all you need to delete it:
import copy
for virus in copy.copy(viruses):
# do stuff with virus
del viruses[virus]
See http://docs.python.org/tutorial/datastructures.html for more information
Upvotes: 0
Reputation: 129507
How about this:
for virus in viruses[:]:
# do stuff
viruses.remove(virus) # remove "virus" from the original list
viruses[:]
creates a copy of our viruses
list. As a note, you can also use list(oldlist)
to copy lists (I find this a little more readable, but either will work). You can read more about lists in python here.
Upvotes: 10
Reputation: 208465
To remove an item by its value just use list.remove()
:
Removing elements from a list while you are iterating over it can cause some unexpected problems, so make sure you are iterating over a copy:
for virus in viruses[:]:
# do stuff
viruses.remove(virus)
Upvotes: 5
Reputation: 250931
lists have a method remove()
, using which you can remove an element by value,
and if you're modifying a list as well as iterating over it then you should use reversed()
, otherwise the iteration will miss some elements:
for virus in reversed(viruses):
viruses.remove(virus)
a simple example:
In [203]: lis=range(0,10)
In [206]: for x in reversed(lis):
.....: if x%2==0: #remove even numbers
.....: lis.remove(x)
.....:
.....:
In [207]: lis
Out[207]: [1, 3, 5, 7, 9]
or use a shallow copy:
In [212]: lis=range(10)
In [213]: for x in lis[:]:
if x%2==0:
lis.remove(x)
.....:
.....:
In [216]: lis
Out[216]: [1, 3, 5, 7, 9]
Upvotes: 1