title: python loop for i in range(n) exceeding specified limit n
body: <p>I am trying to debug a merge method in a program for merge-sort. Here is the method:</p>
  
  <pre><code>def merge(self, leftarray, rightarray):
          n = len(leftarray) + len(rightarray)
          print "len(leftarray) = "+str(len(leftarray))
          print "len(rightarray) = "+str(len(rightarray))
          i = 0
          j = 0
          merged = []
  
          for k in range(n):
              if i == len(leftarray):
                  merged.extend(rightarray[j:])
                  k += len(rightarray[j:])
  
              elif j == len(rightarray):
                  merged.extend(leftarray[i:])
                  k += len(leftarray[i:])
  
              elif leftarray[i] &lt;= rightarray[j]:
                  merged.append(leftarray[i])
                  i += 1
  
              elif leftarray[i] &gt; rightarray[j] :
                  merged.append(rightarray[j])
                  j += 1
  
          return merged
  </code></pre>
  
  <p>The <code>for k in range(n)</code> is the loop exhibiting the problem.
  Here is the debugger trace:</p>
  
  <pre><code>&gt; /home/**/Documents/**/**/merge_sort.py(36)merge()
  -&gt; elif j == len(rightarray):
  (Pdb) n
  &gt; /home/**/Documents/**/**/merge_sort.py(37)merge()
  -&gt; merged.extend(leftarray[i:])
  (Pdb) n
  &gt; /home/**/Documents/**/**/merge_sort.py(39)merge()
  -&gt; k += len(leftarray[i:])
  (Pdb) n
  &gt; /home/**/Documents/**/**/merge_sort.py(30)merge()
  -&gt; for k in range(n):
  (Pdb) p k
  3
  (Pdb) n
  &gt; /home/**/Documents/**/**/merge_sort.py(31)merge()
  -&gt; if i == len(leftarray):
  (Pdb) p n
  3
  (Pdb) 
  </code></pre>
  
  <p>As can be seen in the trace, the value of <code>n</code> is 3 and execution should not enter the loop when <code>k</code> is 3. However execution goes to the line <code>if i == len(leftarray):</code> instead of <code>return merged</code>.</p>