pythonfor-loopindex-error

IndexError: list index out of range in for loop while appending to list


I am trying to combine the first and last items in a list. For example, in a 10 item list, it would have items 1 and 10 combined, items 2 and 9 combined, items 3 and 8 combined, etc. (I am aware that in actual python it would be items 0 and 9, items 1 and 8, etc.)

This is my code to do this:

for x in range(len(numlist)):
    sortlist.append(str(numlist[x]) + "," + str(numlist[len(numlist) - x]))

However, it always gives this error message:

IndexError: list index out of range

When I try using global numlist inside the for loop, it says this:

SyntaxError: name 'numlist' is used prior to global declaration

Why is this?


Solution

  • You are trying to access the last element with the first iteration on x, so x = 0. To fix this problem you can subtract 1 from the length of the list:

    numlist = list(range(10))
    sortlist = []
    
    for x in range(len(numlist)):
        sortlist.append(str(numlist[x] + ',' + str(numlist[len(numlist)-x-1]))
    
    print(sortlist)