Find index of first occurrence in sorted list
<p>I have a sorted list that looks like this:</p>

<pre><code>sortedlist = ['0','0','0','1','1,'1,'2',2','3']
</code></pre>

<p>I also have a count variable:</p>

<pre><code>count = '1'
</code></pre>

<p>*note: sometimes count can be an integar greater that the max value in the list. For example <code>count = '4'</code></p>

<p>What I want to do is to find the first occurrence of the count in the list and print the index. If the value is greater than the max value in the list, then assign a string. Here is what I have tried:</p>

<pre><code>maxvalue = max(sortedlist)
for i in sortedlist:
    if int(count) &lt; int(sortedlist[int(i)]):
        indexval = i
        break
        OutputFile.write(''+str(indexval)+'\n')
if int(count) &gt; int(maxvalue):
    indexval = "over"
    OutputFile.write(''+str(indexval)+'\n')
</code></pre>

<p>I thought the break would end the for loop, but I'm only getting results from the last if statement. Am I doing something incorrectly?</p>

<p>First of all:</p>

<pre><code>for i in range(1, 100):
  if i &gt;= 3:
    break
    destroyTheInterwebz()
  print i
</code></pre>

<p>Will <em>never</em> execute that last function. It will onmy peint <code>1</code> and <code>2</code>. Because <code>break</code> <em>immediately</em> leaves the loop; it does <em>not</em> wait for the current iteration to finish.</p>

<p>In my opinion, the code would be nicer if you used a function <code>indexOf</code> and <code>return</code> instead of <code>break</code>.</p>

<p>Last but not least: the data structures here are pretty expensive. You may want to use integers instead of strings, and numpy arrays. You could then use the very fast <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>numpy.searchsorted</code></a> function.</p>

python list for-loop