0

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.

1
  • Sounds like you should import heapq and use list=heapq.heapify(list) followed by repeated calls to heapq.heappop(list), instead of looping through list to find the minimum by hand and using list.pop(). The heapq module is part of the standard Python library and is built for exactly the purpose of efficiently keeping track of the smallest value in a sequence. Commented Jan 17, 2016 at 21:07

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.