P
P
petrushik2021-11-06 05:22:49
Python
petrushik, 2021-11-06 05:22:49

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

1 answer(s)
M
MaratPetrov96, 2021-11-06
@petrushik

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 question

Ask a Question

731 491 924 answers to any question