Efficient way to find the index of repeated sequence in a list?
<p>I have a large list of numbers in python, and I want to write a function that finds sections of the list where the same number is repeated more than n times. For example, if n is 3 then my function should return the following results for the following examples:</p>

<blockquote>
  <p>When applied to example = [1,2,1,1,1,1,2,3] the function should return [(2,6)], because example[2:6] is a sequence containing all the same value.</p>
  
  <p>When applied to example = [0,0,0,7,3,2,2,2,2,1] the function should return [(0,3), (5,9)] because both example[0:3] and example[5:9] contain repeated sequences of the same value.</p>
  
  <p>When applied to example = [1,2,1,2,1,2,1,2,1,2] the function should return [] because there is no sequence of three or more elements that are all the same number.</p>
</blockquote>

<p>I know I could write a bunch of loops to get what I want, but that seems kind of inefficient, and I was wondering if there was an easier option to obtain what I wanted.</p>

<p>You could use this. Note that your question is ambiguous as to the role of n. I assume here that a series of <em>n</em> equal values should be matched. If it should have at least <em>n+1</em> values, then replace <code>&gt;=</code> by <code>&gt;</code>:</p>

<pre><code>def monotoneRanges(a, n):
    idx = [i for i, v in enumerate(a) if not i or a[i-1] != v] + [len(a)]
    return [r for r in zip(idx, idx[1:]) if r[1] &gt;= r[0]+n]

# example call
res = monotoneRanges([0,0,0,7,3,2,2,2,2,1], 3)

print(res)
</code></pre>

<p>Outputs:</p>

<pre><code>[(0, 3), (5, 9)]
</code></pre>

python python-3.x