You're deleting elements in the list as you're iterating over it. So, for example, by the time you reach index 999
, there are no longer 1000
elements in the list. (In truth, this out-of-bounds issue happens at a much earlier index.)
Rather than try to modify the list as you're iterating over it, you should create a new list instead. The easiest way of doing that is to use filter()
to remove numbers on a specified condition; in this case, we remove numbers that contain a 1
, 4
, or 5
:
def contains_forbidden_digit(num):
for digit in str(num):
if digit in {'1', '4', '5'}:
return True
return False
print(list(filter(lambda x: not contains_forbidden_digit(x), range(1000))))