Check if values in list exceed threshold a certain amount of times and return index of first exceedance
<p>I am searching for a clean and pythonic way of checking if the contents of a list are greater than a given number (first threshold) for a certain number of times (second threshold). If both statements are true, I want to return the index of the first value which exceeds the given threshold.</p>

<p><strong>Example</strong>:</p>

<pre><code># Set first and second threshold
thr1 = 4
thr2 = 5

# Example 1: Both thresholds exceeded, looking for index (3)
list1 = [1, 1, 1, 5, 1, 6, 7, 3, 6, 8]

# Example 2: Only threshold 1 is exceeded, no index return needed
list2 = [1, 1, 6, 1, 1, 1, 2, 1, 1, 1]
</code></pre>

<p>A naive and straightforward approach would be to iterate over the list counting the number of items greater than the first threshold and returning the index of the first match if the count exceeds the second threshold:</p>

<pre><code>def answer(l, thr1, thr2):
    count = 0
    first_index = None
    for index, item in enumerate(l):
        if item &gt; thr1:
            count += 1
            if not first_index:
                first_index = index

            if count &gt;= thr2:  # TODO: check if "&gt;" is required instead
                return first_index

thr1 = 4
thr2 = 5

list1 = [1, 1, 1, 5, 1, 6, 7, 3, 6, 8]
list2 = [1, 1, 6, 1, 1, 1, 2, 1, 1, 1]

print(answer(list1, thr1, thr2))  # prints 3
print(answer(list2, thr1, thr2))  # prints None
</code></pre>

<p>This is probably not quite pythonic though, but this solution has couple of advantages - we <em>keep the index of the first match only</em> and have an <em>early exit out of the loop</em> if we hit the second threshold.</p>

<p>In other words, we have <code>O(k)</code> in the best case and <code>O(n)</code> in the worst case, where <code>k</code> is the number of items before reaching the second threshold; <code>n</code> is the total number of items in the input list.</p>

python list iterator threshold