Python: Cross Connecting a loop within a loop
<p>Just for practice, I am trying to write a function in python which contains a loop within a loop. However I get an <code>IndexError: list index out of range</code></p>

<p>Here's the function</p>

<pre><code>def merge(A,B):
    c = []
    k = 0
    i = 0
    j = 0
    while i &lt; len(A):
        while j &lt; len(B):
            if A[i] &lt;= B[j]:
                c.append(A[i])
                i+=1
                print c
                print i
                print k
                k=j
            else:
                c.append(B[j])
                j+=1
        c.extend(A[i:])
        return c
    c.extend(B[k:])
    return c 
</code></pre>

<p>Here's the error</p>

<pre><code>merge([1,8,9],[2,3,4,11])
[1]
1
0
[1, 2, 3, 4, 8]
2
0
[1, 2, 3, 4, 8, 9]
3
3

Traceback (most recent call last):
  File "&lt;pyshell#51&gt;", line 1, in &lt;module&gt;
    merge([1,8,9],[2,3,4,11])
  File "&lt;pyshell#49&gt;", line 8, in merge
    if A[i] &lt;= B[j]:
IndexError: list index out of range
</code></pre>

<p>You are incrementing i or j in the if statement in the middle - with your sample data, if i is already <code>len(A)-1</code>, i.e. 2 and is incremented when j &lt; <code>len(B)-1</code>, because the <code>while j &lt; len(B)</code> will continue to execute, and on the next time round the loop of course <code>i</code> is out of bounds to index into A. You can see in your console output that i is 3 when the error happens. If you had put "i=" and "j=" before the value in the print statement and also print len(A) and len(B), it would be more obvious, but all the information to diagnose the bug in your code is already in your console output.</p>

<p>I leave you the exercise of working out how to make your code not cause the error.</p>

python python-2.7 python-3.x