Mark Sfeir Mark Sfeir - 4 years ago 121
Python Question

Avoiding an indexing error in Python while looping

Regardless of whether this is the most efficient way to structure this sorting algorithm in Python (it's not), my understandings of indexing requirements/the nature of the built-in 'min' function are failing to account for the following error in the following code:


Error:
builtins.IndexError: list index out of range


Here's the code:

#Create function to sort arrays with numeric entries in increasing order
def selection_sort(arr):
arruns = arr #pool of unsorted array values, initially the same as 'arr'
indmin = 0 #initialize arbitrary value for indmin.
#indmin is the index of the minimum value of the entries in arruns
for i in range(0,len(arr)):
if i > 0: #after the first looping cycle
del arruns[indmin] #remove the entry that has been properly sorted
#from the pool of unsorted values.
while arr[i] != min(arruns):
indmin = arruns.index(min(arruns)) #get index of min value in arruns
arr[i] = arruns[indmin]

#example case
x = [1,0,5,4] #simple array to be sorted
selection_sort(x)
print(x) #The expectation is: [0,1,4,5]


I've looked at a couple other index error examples and have not been able to attribute my problem to anything occurring while entering/exiting my while loop. I thought that my mapping of the sorting process was sound, but my code even fails on the simple array assigned to x above. Please help if able.

Answer Source

arr and arruns are the same lists. You are removing items from the list, decreasing its size, but leaving max value of i variable untouched.

Fix:

arruns = [] + arr

This will create new array for arruns

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download