The elephant in the room, here, is that none of the responses dealt with the question, only provided alternate code. That is not much help, imho.
Now to the actual question, let one ask another, preliminary question:
What happens to the list after we del
an item; and, how does that relate to the current iteration pointer?
We need to give this some thought. I’ll wait for your reply.
While I’m waiting, here is some preliminary reading:
5. Data Structures — Python 3.11.3 documentation
Also, consider that we are not deleting an item, but deleting the reference to it. Consider this recursive function:
def remove_between(my_list, start, end):
for num in my_list:
if num > start and num < end:
del my_list[my_list.index(num)]
return remove_between(my_list, start, end)
return my_list
>>> print (remove_between([3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5, 10))
[3, 4, 5, 10, 11, 12]
>>> from random import randint as rand
>>> y = [rand(1, 100) for x in range(10)]
>>> print (sorted(remove_between(y, 25, 75)))
[13, 17, 80, 81, 84, 97]
>>>
def mix(a, b, c=10):
return [rand(a, b) for _ in range(c)]
>>> sorted(remove_between(mix(1, 100), 25, 75))
[2, 5, 7, 83, 83, 96]
>>> sorted(remove_between(mix(1, 100), 25, 75))
[13, 14, 15, 25, 92]
>>> sorted(remove_between(mix(1, 100), 25, 75))
[4, 5, 12, 75, 78, 100]
>>> sorted(remove_between(mix(1, 100), 25, 75))
[16, 76, 96]
>>>
I’ll explain more when you get back to us.