Insertion sort not working - list index out of range
<p>Trying to create insertion sort but receive an error...</p>

<p>Don't really know why it is happening. It always tends to miss 37 aswell</p>

<pre><code>numbers = [45,56,37,79,46,18,90,81,50]

def insertionSort(items):
    Tsorted = []
    Tsorted.append(items[0])
    items.remove(items[0])
    for i in range(0,len(items)):
        print (Tsorted)
        if items[i] &gt; Tsorted[len(Tsorted)-1]:
            Tsorted.append(items[i])
        else:
            Tsorted[len(Tsorted)-2] = items[i]
        items.remove(items[i])

insertionSort(numbers)
</code></pre>

<p>Error:</p>

<pre><code>    if items[i] &gt; Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
</code></pre>

<p>You are removing elements from <code>items</code> over the course of the loop; thus, <code>i</code> may become a value that was a valid index in the original <code>items</code>, but is no longer in the shortened one.</p>

<p>If you need to remove elements from <code>items</code>, it looks like you should wait until the loop is finished.</p>

python python-2.7 insertion-sort