Answer the question
In order to leave comments, you need to log in
IndexError: list index out of range?
Why does this script throw an IndexError: list index out of range error?
import numpy as np
dummy = [1, 1, 5, 6, 7, 9, 4, 4, 2]
x = 1
for j in range(len(dummy)):
if dummy[j] == dummy[j+ 1]:
dummy[j] = 0
print(dummy)
Answer the question
In order to leave comments, you need to log in
Hello!
Everything is very simple! When the loop gets to the last number, which is 8, which is the index of the last element, you tell the code to check
dummy[8] == dummy[9]
But there is no element at index 9, so that's the IndexError.
Also, you apparently forgot to make dummy numpy an array, otherwise why import numpy?
And instead of range(len()) it is better to use enumerate
import numpy as np
dummy = np.array([1, 1, 5, 6, 7, 9, 4, 4, 2])
x = 1
for n,j in enumerate(dummy[:-1]):
if dummy[n] == dummy[n+1]:
dummy[j] = 0
print(dummy)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question