One way to avoid the issue you've encountered is to iterate over the list in reverse. That way, the current index is independent of deletions for elements with greater indices.
list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
for index in reversed(range(len(list_example))):
if list_example[index] == 'a':
del list_example[index]
Another way to remove elements, if you don't need to modify the list in-place, is to use a list comprehension combined with a condition (if x != 'a'
).
list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
list_example = [x for x in list_example if x != 'a']
Additionally, Python has a filter
function, which takes a function for specifying elements to drop.
list_example = ['a', 'a', 'a', 'a', '(', 'a', 'a', ')']
list_example = list(filter(lambda x: x != 'a', list_example))