4

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?

0

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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)

Comments

1

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]

Comments

0

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

1 Comment

You can't change a dictionary while you're iterating it. RuntimeError: dictionary changed size during iteration

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.