CustomerSupport CustomerSupport - 3 months ago 19
Python Question

Insertion-sort error in Python

I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:

line 16, in <module> if listNums[x] < listNums[i]:


For this program:

listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38]

x = 1
i = 0
Copy = 0

for z in range (0, len(listNums)):
if listNums[x] < listNums[i]:
Copy = listNums[i]
listNums[i] = listNums[x]
listNums[x] = Copy
i = i + 1
x = x + 1

print(listNums)

Answer

Chances are it's a bounds error because x eventually increments up to len(listNums) which is 1 beyond the bounds of the zero-indexed array.

Try only iterating through range(0, len(listNums)-1).