greyvest
greyvest

Reputation: 33

Insert Sort Index Error?

I'm attempting to create an insert Sort which takes the smallest number from a list and appends it to another list.

The problem is, everything I attempt to pop() the number out of the list, I get an index error.

Here's my code:

alist = [2,9,8,6,1]
blist =[] 

def insertsort(list, slist) :
    for item in list:
       smallest = list[0] 
       if item < smallest:
           smallest = list[item] 
       list.pop(smallest) 
       slist.append(smallest) 

insertsort(alist, blist) 

print(blist) 

And the error is:

IndexError: pop index out of range

Thanks in advance for any help.

Upvotes: 0

Views: 40

Answers (1)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19219

When a function call fails, reads the docs, or use, in this case, >>> help(list.pop). Much faster that waiting hours for someone to answer a trivial question.

The argument to pop is an index of a value in the list, not a value itself. Your code has several other problems once this is fixed.

alist = [2,9,8,6,1]
blist =[] 

def insertsort(inlist, outlist):
    while inlist:
        it = iter(inlist)
        sdex = 0
        small = next(it)
        for dex, item in enumerate(it, 1):
           if item < small:
               sdex = dex
               small = item
        inlist.pop(sdex)
        outlist.append(small) 

insertsort(alist, blist) 

print(blist)

prints [1, 2, 6, 8, 9]

The following version of the function uses the builtin min function and gives the same output.

def insertsort(inlist, outlist):
    while inlist:
        small = min(inlist)
        inlist.pop(inlist.index(small))
        outlist.append(small)

Upvotes: 1

Related Questions