Many of answers involve creating a new list. This involves copying all the data from the old list to the new list (except for the removed items). If your list is huge, you may not be able to afford it (or you should not want to).
In these cases, it is much faster to alter the list in place. If you have to remove more than 1 element from the list it can be tricky. Suppose you loop over the list, and remove an item, then the list changes and a standard for-loop will not take this into account. The result of the loop may not be what you expected.
Example:
a = [0, 1, 2, 3, 4, 5]
for i in a:
a.remove(i) # Remove all items
print(a)
Out: [1, 3, 5]
A simple solution is to loop through the list in reverse order. In this case you get:
a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
a.remove(i) # Remove all items
print(a)
Out: []
Then, if you need to only remove elements having some specific values, you can simply put an if statement
in the loop resulting in:
a = [0, 1, 2, 3, 4, 5]
for i in reversed(a):
if i == 2 or i == 3: # Remove all items having value 2 or 3.
a.remove(i)
print(a)
Out: [0, 1, 4, 5]
except
is bad practice. Useexcept Exception
at a minimum. – wjandrea