The reason why it doesn’t work is that the for
loop steps though the list, one element at a time, with the indexes 0, 1, 2, etc.
When you delete an element, the later elements shift down to fill the gap.
So, suppose you had [‘a’, ‘b’, ‘c’], for example.
You look at element 0, which is ‘a’, and decide to remove it.
You now have [‘b’, ‘c’].
You then look at the next element, element 1, which is ‘c’.
Unfortunately, you’ve just skipped over ‘b’.
The for
loop didn’t notice that you’ve changed the list.
It’s generally recommended to make a new list instead:
list1 = [1, 2, 5, 4, 3, 5, 5, 6, 7, 8, 5, 5, 5, 9]
new_list = []
for i in list1:
if i != 5:
new_list.append(i)
list1 = new_list # Or maybe list1[ : ] = new_list
print(list1)