'IndexError: string index out of range - For loop checking the current and next item

def add(nums):

    sum = 0
    pointer = 0

    for item in nums:
        if item[pointer] > item[pointer+1]:
            sum += int(item)
            pointer += 1
        else:
            pointer += 1

    return sum


list = ['5', '7', '6', '4', '3', '7', '8']

print(add(list))

Error: if item[pointer] > item[pointer+1]: IndexError: string index out of range

Im trying to check if the next item in the list is greater or less than the item before.

If the item before is greater than the next item then it is added to sum and then returned.

However, I get this error. Any help would be much appreciated.



Solution 1:[1]

You are trying to compare the last entry in your list with a following entry (pointer + 1). But there is no following entry.

Solution 2:[2]

Are you looking for something like this?

def add(nums):

    sum = 0
    pointer = 0


    for item in nums:
        try:
            if int(item) > int(nums[pointer + 1]):
                sum += int(item)
            
            pointer += 1
        except IndexError:
            pass


    return sum


source = ['5', '7', '6', '4', '3', '7', '8']

print(add(source))
# Output: 17

you should use a try/except block as you're gonna encounter an IndexError on the last iteration. You could also use a simple if statement to check for it, but in my opinion this is the best and simplest way to go about it.

Solution 3:[3]

Every item in nums list is one character string. So there can only be index 0 for a single item. During first iteration as program reaches line if item[pointer] > item[pointer+1], right part item[pointer+1] has index of 1 i.e. pointer here is 1, which doesn't exist for item.

Solution 4:[4]

1.Your values are of the string type, and you mean a number in the check.

2.Because in the last comparison you are referring to a non-existent value in the index. The length of the array is 7, and the index 'nums[item+1]' is requested 8(IndexError: string index out of range). Therefore, in the loop I stop at the penultimate value 'len(nums)-1)'.

 def add(nums):

    sum = 0

    for item in range(0, len(nums)-1):
        if int(nums[item]) > int(nums[item+1]):
            sum += int(nums[item])

    return sum


list = ['5', '7', '6', '4', '3', '7', '8']

print(add(list))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elec1
Solution 2 dharmey
Solution 3 WyzPanda
Solution 4