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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With