list1 = ['a','b','c','d','e'] for x in range(len(list1)): if list1[x] == 'c': list1.pop(x)
The above code is an idea to explain the task what Iam performing. I have a list that Iam looping through when it finds something or meet some condition it will delete that specific index element accordingly.
For instance if it finds element ‘c’ in the list then it will delete it from the list but it throws an IndexError: list index out of range
. I need help to get an idea that can i re-set my loop so that it will loop through the next element without any error for instance once it pass through a, b it will find c and delete then without IndexError
it should go and check remaining elements ‘d’ and ‘e’.
if the loop deletes any element it should check the next iteration without error, any suggestions that i can try?
Advertisement
Answer
You may enjoy the filter
function.
def myCondition(x): return x == 'a' list1 = ['a','b','c','d','e'] list1 = list(filter(myCondition, list1))
Note that myCondition
retains those “True” elements, so if you want to delete them, you need to flip the condition. This has a slight overhead since it’s creating a new Iterable, but I don’t think it matters in this specific scenario.