Home > Back-end >  Index error when trying to compare values in a list
Index error when trying to compare values in a list

Time:11-12

I'm trying to find the remainder of each number in a list that is equal to one, but the problem is I get an index error

Here I compare the current item in the list to the next one:

numbers = [1,2,3,4,5,6]

sorted_number = sorted(numbers)

for index, num in enumerate(sorted_number):
    if sorted_number[index   1] % sorted_number[index] == 1:
        print(index, num)

CodePudding user response:

When you get to the last element of sorted_number, the call sorted_number[index 1] is out of bounds. You can avoid this by only iterating to the second to last number in the list:

for index, num in enumerate(sorted_number[:-1]):
    if sorted_number[index   1] % sorted_number[index] == 1:
        print(index, num)

CodePudding user response:

You are getting index error because the index 1 is greater than sorted_number lengh, so you need to add a check for that case

for index, num in enumerate(sorted_number):
    if index < len(sorted_number) - 1:
        if sorted_number[index   1] % sorted_number[index] == 1:
            print(index, num)
  • Related