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>Your logic is wrong, you have a so called <em>sorted list</em> of strings which unless you compared as integer would not be sorted correctly, you should use <em>integers</em> from the get-go and <a href="https://docs.python.org/2/library/bisect.html#bisect.bisect_left" rel="nofollow">bisect_left</a> to find index:</p>

<pre><code>from bisect import bisect_left

sortedlist = sorted(map(int, ['0', '0', '0', '1', '1', '1', '2', '2', '3']))

count = 0

def get_val(lst, cn):
    if lst[-1] &lt; cn:
        return "whatever"
    return bisect_left(lst, cn, hi=len(lst) - 1)
</code></pre>

<p>If the value falls between two as per your requirement, you will get the first index of the higher value, if you get an exact match you will get that index:</p>

<pre><code>In [13]: lst = [0,0,2,2]

In [14]: get_val(lst, 1)
Out[14]: 2

In [15]: lst = [0,0,1,1,2,2,2,3]

In [16]: get_val(lst, 2)
Out[16]: 4

In [17]: get_val(lst, 9)
Out[17]: 'whatever'
</code></pre>

python list for-loop