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.