0

I am new to python and I stumbled across this issue where I keep getting IndexError: list index out of range for if (numbers[x] % n == 0) when I looped through a list of integers and tried to remove those that are multiples of n even though I can print out numbers[x] normally without encountering this error.

def remove_multiples_of(numbers, n):
    for x in range(len(numbers)):
        if (numbers[x] % n == 0):
            numbers.pop(x)
    return (numbers)

values = [5, 3, 1, 2, 3]
remove_multiples_of(values, 3)
print(values)

Alternatively, this somehow works where I don't get the error but once I add numbers.pop(x) I get the error for the line before instead:

def remove_multiples_of(numbers, n):
    for x in range(len(numbers)):
        if (numbers[x] % n == 0):
            print ("WORKS")
    return (numbers)

values = [5, 3, 1, 2, 3]
remove_multiples_of(values, 3)
print(values)

Could someone please explain to me what I am doing wrong and if there are any other more efficient ways to complete the task? Thanks in advance for the help.

  • Don't mutate the list you are looping through. That is what you are doing wrong. Remove the unwanted elements from a copy of the list. – BoarGules Jul 25 '21 at 12:26
  • @BoarGules Why can't I mutate through it and when should I be creating a copy of a list instead of mutating the actual list? Also, why is the error line for the if statement and not the code where the list is getting mutated? – user11950757 Jul 26 '21 at 09:13
  • It is not an error to mutate the list. But removing elements from the list changes its length, on the fly. Meanwhile, your loop goes through `range(len(numbers))` which in your example evaluates to `[0,1,2,3,4]` and that does not change even when the length of the list does. So when the loop evaluates `numbers[x]` and `x` has the value `4` you get an `IndexError`. The behaviour can be explained, but it is hard to reason about accurately, as you have discovered, and so it is simpler to adopt the simple rule of thumb: *don't mutate the list you are looping through.* – BoarGules Jul 26 '21 at 09:31

0 Answers0