Issue
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)
Solution
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)
Answered By - jprebys
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.