May-11-2021, 11:58 AM
Don't modify an iterator while you're iterating over it,it's a known bad patternđź’€
Will mess up list index and will get your result.
Could add
The solution is to make a new list,then therew is no
Will mess up list index and will get your result.
Could add
enumerate(l2[:])
to make it work,but still no t good as as remove()
has to go over the whole list for every iteration O(n^2)
.The solution is to make a new list,then therew is no
remove()
(that rarely ever need to be used) used in the loop.l2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a = 1 result = [] for ind, el in enumerate(l2): if el != a: result.append(el) print(result)
[0, 2, 3, 4, 5, 6, 7, 8, 9]Or list comprehension.
>>> l2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [el for el in l2 if el != 1] [0, 2, 3, 4, 5, 6, 7, 8, 9]