In this code snippet:
while i2 <= len(number_list):
while number_list[i] <= number_list[i2]:
i2 = i2+1
In the first while
, i2
finally reaches as value an index that does not exist. You have to change the condition to avoid the last value.
On the other hand, the second while
is increasing i2
without checking if the end of the list has been reached.
Likewise, the list you pass as an argument is altered in the process by losing elements as you do del number_list[i]
. Irremediably there will come a time when the list is empty and that this del
produces error.
Assuming you want to make your own sorting algorithm, without using python facilities like sorted
, min
or max
, still let me advise you a couple of things:
- Never, never, never use external variables as a result of a function. Every function should return its result by
return
- Use
for
before while
to go through a list
- Modifying a list while it is being processed is often the cause of numerous errors. The list that you pass to order is destroyed inside the function, shortening in length and losing elements.
Maintaining the function as recursive (which would not be necessary), a possible rewrite would be like this:
def order_number_list(number_list):
if len(number_list) == 0:
return number_list
else:
m = number_list[0]
for i in range(1, len(number_list)):
if m > number_list[i]:
m = number_list[i]
return [m] + order_number_list(number_list[1:])
number_list_final = order_number_list(number_list)
Although no recursion is better:
def order_number_list(number_list):
lst = number_list[:] # copia de la lista
for i in range(1, len(lst)):
for j in range(i, len(lst)):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
return lst