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>You could use a function (using <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">EAFP</a> principle) to find the first occurrence that is equal to or greater than the count:</p>

<pre><code>In [239]: l = ['0','0','0','1','1','1','2','2','3']

In [240]: def get_index(count, sorted_list):
     ...:     try:
     ...:         return next(x[0] for x in enumerate(l) if int(x[1]) &gt;= int(count))
     ...:     except StopIteration:
     ...:         return "over"
     ...:     

In [241]: get_index('3', l)
Out[241]: 8

In [242]: get_index('7', l)
Out[242]: 'over'
</code></pre>

python list for-loop