l = ["a", "b", "c", "d", "e"]
for item in l[:]:
if item == "b":
l.remove(item)
print(l)
#the main trick of this problem is the traditional for loop will not work...it will give an "out of range" error saying
#this is because you are changing the list that you are for looping
#the traditional for loop will not work because you are changing the list it is iterating
# Remove elements from a list while iterating
# What not to do
a = [1, 2, 2, 3, 4]
def even(x): # helper function
return x % 2 == 0
for i in a:
if even(i):
a.remove(i) # never loop over a list and remove elements at the same time
a #[1, 2, 3] <= 2 is still here.
# Problem: removed an element while looping over it,
# so all elements after the removed element are shifted one place to the left, so we skip 1 iteration.
# the right way is to loop over a copy of the list
# Approach 1: loop over a copy of the list
a = [1, 2, 2, 3, 4]
for i in a[:]: # loop over a copy of the list
if even(i):
a.remove(i)
a #[1, 3]
# Approach 2: use list comprehension to create a new list
a = [x for x in a if not even(x)] # [1, 3]
# Faster way, assign in slice of a, so modify in place
a[:] = [x for x in a if not even(x)] # [1, 3]
# Approach 3: use filter
from itertools import filterfalse
a[:] = filterfalse(even, a) # [1, 3]