-2
#list 000 to 999
numbers = []
for i in range(0, 1000):
    i = str(i).zfill(3)
    numbers.append(i)

num = "145"
for j in range(1000):
    for k in range(3):
        if numbers[j][k] in num:
            numbers.remove(numbers[j])

I want to delete all the numbers that have 1, 4 or 5 in them

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
rastin
  • 1
  • You removed some elements of `numbers`, so it no longer contains 1000 elements, so `for j in range(1000)` is no longer valid. – Pranav Hosangadi Feb 10 '22 at 23:45
  • 1
    After you remove an item from `numbers`, it no longer has 1000 items in it. The best plan when doing something like this is to create a NEW list that contains only the items you want to keep. And you can rewrite your loops as `for j in numbers:` / `for k in j:` if j in num:`... – Tim Roberts Feb 10 '22 at 23:46
  • Removing an element from `numbers` makes it smaller (obviously), so the `range(1000)` loop will eventually result in indexes that are too big. – John Gordon Feb 10 '22 at 23:46

2 Answers2

1
numbers = []
for i in range(0, 10000):
    i = str(i).zfill(3)
    numbers.append(i)
print('1', numbers)
num_del = "145"
for num in numbers:
    for i in num_del:
        if i in num:
            numbers.remove(num)
print('2', numbers)
Marya
  • 170
  • 1
  • 8
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/31042287) – excitedmicrobe Feb 11 '22 at 06:34
  • You're right. That's why I am trying to get enough reputation. @excitedmicrobe – Marya Feb 11 '22 at 16:02
0

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))))
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33