"List index out of range error"

Okay so for context the variable arr in this problem is just a space separated list of random numbers and I am trying to select the second largest value in the list of random numbers. My code is:

    my_list = []

    for i in arr:
        my_list.append(i)

    my_list.sort(reverse=True)

    for x in range(len(my_list)):
        if my_list[x] != my_list[x+1]:
            print(my_list[x+1])

I get the error “IndexError: list index out of range” but I don’t see how.

My second loop I should be looping through a list that starts at zero and ends at the length of the original array minus one. The proceeding if statement should catch the first instance where consecutive numbers are not equal and, because I ordered the list, it should also be the second largest value.

Can someone explain the error I am getting?

Hi there :slight_smile:

It sounds like your arr variable is a list holding a string element with numbers separated by spaces (or even a string? - if yes see the last paragraph first). If it is the case (which I don’t know because I can’t see the content of arr), then you need to split the string into a list of elements:
new_list_of_str_numbers = arr[0].split()
This will cut in place of spaces, so you will have a list of string values representing numbers. If you want to use the string values as actual numbers then you’ll also have to convert them to float or int as you are appending your my_list variable:

for num_str in new_list_of_str_numbers:
    num_int = int(num_str)
    my_list.append(num_int)

Then you should be able to perform the rest of your operations.
Type conversions are built into python.

BTW if your arr is something else than I assumed e.g it’s a string of numbers and not a list containing a string, then you’d do arr.split() instead of arr[0].split()
Let me know if it answers your questions, and it would be nice if you can post what is the output ofprint(type(arr))

1 Like

I was also wondering about the things @lael.j.h mentioned above, if arr is very long maybe shorten it for now so you can post it here and we can know what exactly we are working with.

That being said, even if arr is a simple list of integers you are still going to get an IndexError. Maybe if we add an extra print statement it will be easier to see why.

my_list = [1, 2, 3, 4, 5]

for x in range(len(my_list)):
    if my_list[x] != my_list[x+1]:
        print(my_list[x], my_list[x+1])
Output:
1 2
2 3
3 4
4 5
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    if my_list[x] != my_list[x+1]:
IndexError: list index out of range

if it helps this is above my code and it came this way (its a problem from hackerrank: https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem)

if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())

The code that I have in the previous post follows this. Check out the link to the problem. I’m pretty sure arr is just integers separated by a space.

I still don’t see why it gives this error here.

Here is my thinking:
during the first iteration through the loop, it will assign the 0 to x since that is the first item in the list generated by by range(len(my_list)). Therefore, my_list[ x ] should be == my_list[0] and my_list[x+1] should be my_list[1]. I don’t see anything wrong with this indexing and should compare the first item in my list to the second item, no?

Sorry I made a mistake and didn’t originally include the full output, just the error.
Take a look again and take note of the numbers printed before the error occurs.

1 Like

So there is nothing stopping the loop from ceasing once it finds the second highest. It just continues iterating through until it reaches [len(list)+1] which the index doesn’t exist. I needed to add a return statement (if its a function) or a break statement.

I use this and it worked:

n = int(input())
    arr = map(int, input().split())

    my_list = []

    for i in arr:
        my_list.append(i)

    my_list.sort(reverse=True)

    for x in range(len(my_list)):
        if my_list[x] != my_list[x+1]:
            print(my_list[x+1])
            break

Thanks so much for taking the time to show me what was wrong :slight_smile:

Happy to help. Although there is still a bug in the code that will occur if you reach the end of the list and your if my_list[x] != my_list[x+1]: statement never evaluates to True. Also it will stop the for loop from going through the full list as soon as this condition is met, which you may or may not want it to do.

With the break statement included, if we change my_list to

my_list = [1, 1, 1, 1, 1]

and run the for loop, you will still get an IndexError. Look at the if statement inside of the for loop and consider the indexes it is trying to compare when it reaches the end of the list.

Explanation if you need it:

Using the values in my_list above, once the for loop has reached the final index(4) the if statement would be

if my_list[4] != my_list[5]:

Since the list only has 4 indexes, when it tries to access my_list[5] an IndexError occurs.

1 Like

If you subtract 1 from the range, the code should work.

We must be careful when adding 1 to an index since the index ends where the range ends. One plus will eventually point to an element that does not exist.

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.