Zedekiah Ochieng
Zedekiah Ochieng

Reputation: 11

IndexError: list index out of range in python while using greater than operator

I'm checking if the element in the first index is greater than its corresponding element in the next index. if it is greater to be added into the new list.

Here is the code.

def solution(A):
    row1 = []
    for index in range(len(A)):
        if A[index] > A[index + 1]:
            row1.append(A[index])

    return row1


print(solution(A=[5, 4, 3, 6, 1]))
Traceback (most recent call last):
  File "/home/zeddy/PycharmProjects/pythonProject1/index.py", line 11, in <module>
    print(solution(A=[5, 4, 3, 6, 1]))
  File "/home/zeddy/PycharmProjects/pythonProject1/index.py", line 5, in solution
    if A[i] > A[i + 1]:
IndexError: list index out of range

Process finished with exit code 1

I tried using enumerate function but the same problem occurs I'm expecting to get the a new list containing elements which are greater.

Upvotes: 0

Views: 54

Answers (1)

Ayan Akkassov
Ayan Akkassov

Reputation: 11

According to this answer. You are trying to reach the non-existing element.

A[index + 1]

in the last step of the iteration, you will get IndexError. Use range(len(A) - 1) instead.

Upvotes: 1

Related Questions