nateph
nateph

Reputation: 1187

Why is this going out of range?

I am getting a IndexError: list index out of range error. I'm not sure why. Any advice?

The code is trying to see if a list of numbers is an arithmatic progression, in this case every number is added by 2.

def is_arith_progession(num_list):

    delta = num_list[1] - num_list[0]
    for num in num_list:
        if not (num_list[num + 1] - num_list[num] == delta):
        return False
    else:
        return True

print(is_arith_progession([2, 4, 6, 8, 10]))

Upvotes: 0

Views: 455

Answers (4)

Matt Messersmith
Matt Messersmith

Reputation: 13747

This:

for num in num_list:
    if not (num_list[num + 1] - num_list[num] == delta):
        return False

almost certainly doesn't do what you think it does. When you define for num in num_list:, this means that num is an item from the list num_list. num is NOT an index. So, if your list is [2, 4, 6, 8, 10], you go out of bounds when num is 4 (i.e. the second item in your list), because your input list is only length 5 and you try to access index num+1, which is 5 (indexes are 0 based, so 5 is out of bounds)

You probably want something like this:

# Start at index 1, or you'll always return false since delta == index1 - index0
for index in range(1, len(num_list)-1):
    if not (num_list[num + 1] - num_list[num] == delta):
        return False

or the more pythonic (note there are no indices):

# Again start at index1, zip will handle the edge case of ending nicely so we don't go OB
for num, next_num in zip(num_list[1:], num_list[2:]):
    if not (next_num - num == delta):
        return False

Upvotes: 2

Seljuk Gulcan
Seljuk Gulcan

Reputation: 1868

You are trying access 5th element of num_list array in the second iteration of for loop. After the first iteration num becomes 4, so program crashes when it tries to evaluate num_list[num + 1].

num variable holds the actual element in the list. It is not index to element.

To iterate over indices, you may try for num in range(len(num_list) - 1) which should solve the issue. (Note -1 in the paranthesis)

Upvotes: 2

IcedLance
IcedLance

Reputation: 426

2 things:

  • num is an element of num_list, not just an index. Getting an index would be for num in range(len(num_list)):, you're effectively calling num_list[num_list[i]];
  • Even if it was an index, for the last index num in array you are calling numlist[num+1], which is out of array bounds as num is already last;

Do for INDEX in range(len(num_list)-1): and if not (num_list[INDEX + 1] - num_list[INDEX] == delta):. That should do it.

Upvotes: 1

blue note
blue note

Reputation: 29081

You are iterating over the values, not the indexes of the array. So, num_list[num] can be out of range. Since you refer to the i+1 element, iterate up to i < n-1

for i, _ in enumerate(num_list[:-1]):
    if num_list[i+1] - num_list[i]...

Upvotes: 1

Related Questions