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><code>range(0,len(items)</code> will only be calculated the first time your code hits your for-loop, at which state <code>len(list) = 8</code>. Which means that you wlil iterate</p>

<pre><code>for i in [0,1,2,3,4,5,6,7]
    #Do stuff...
</code></pre>

<p>But at the same time you remove items from your list in each loop. So when hitting i = 4, you have iterated your loop 4 times and the length of you <code>item</code>-list is only 4, which means that <code>items[4]</code>
 no longer exists.</p>

python python-2.7 insertion-sort