Search code examples
pythonindex-error

Index out of range error when trying to access the last index


I am doing leetcode and my code is giving me this error that I can't make sense of. I am asked to reverse the integer, which is fairly simple to do. These are the test cases:

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

I figured that all I need were if-statements to check the condition of the input so here is what I did:

class Solution:
    def reverse(self, x: int) -> int:
        string = str(x)
        lst = list(string)

        lst.reverse()

        if((lst[0]) == '0'):
            lst.pop(0)

        if((lst[-1] == '-')):
            lst.pop(-1)
            lst.insert(0, '-')

        output = ''.join(lst)

        return output

But this line if((lst[-1] == '-')): is throwing an IndexError: list index out of range error. All I'm doing is accessing the last element of the list. I am not trying to access an index which doesn't exist.

The only thing that I need to know is why this error is happening. Because this is leetcode, I'd like to fix the code myself.

Final Code

class Solution:
    def reverse(self, x: int) -> int:
        lst = list(str(x))

        lst.reverse()

        if(x < 0):
            lst.pop(-1)
            lst.insert(0, '-')

        int_output = int(''.join(lst))

        if(int_output < (2**32)):
            return int_output
        else:
            return 0

Solution

  • This error will happen if lst is empty, since any index will be out of range.

    If x was originally "0", then lst will be ["0"]. The first if statement will then remove the "0" element, so now it will be [], which is an empty list, and you'll get that error.

    If you're doing 7. Reverse Integer you have other problems. It says that the result should be an integer, but you're returning a string. You also only remove the first 0. If the input is 12000 you'll return "0021" instead of 21.