Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Element From List Without Index

Tags:

python

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?

like image 770
user1427661 Avatar asked Dec 09 '22 20:12

user1427661


1 Answers

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.

like image 130
arshajii Avatar answered Dec 11 '22 10:12

arshajii