Digit Pattern matching
<p>I have a list:</p>

<pre><code>a = [1, 2, 4, 5, 8, 2, 4, 2, 4, 6, 7]
</code></pre>

<p>I would like to count how many times <code>2, 4</code> appear together </p>

<pre><code>( 2 at index i and 4 at index i+1). 
</code></pre>

<p>How can I do that? </p>

<p>In order to do that you'd need to check every pair in your given list to see if the pair contains <code>2</code> and <code>4</code>. In Python, you can create pairs by using the <code>zip</code> built-in function. </p>

<p>In order to create adjacent pairs, we supply the list <code>a</code> as the first argument to <code>zip</code> and the <em>same list</em> one position forward:</p>

<pre><code>list(zip(a, a[1:]))  # a[1:] is [2, 4, 5, 8, 2, 4, 2, 4, 6, 7]
</code></pre>

<p>This produces pairs of the form:</p>

<pre><code>[(1, 2), (2, 4), (4, 5), (5, 8), (8, 2), (2, 4), ...]
</code></pre>

<p>Now, what we can do is <em>iterate through</em> these pairs (using <code>for</code>), unpack them to variables (<code>i</code> and <code>j</code>) and test our condition (one is equal to <code>2</code> and the other to <code>4</code>). This looks like this:</p>

<pre><code>[i == 2 and j == 4 for i, j in zip(a, a[1:])]
</code></pre>

<p>This creates a list with <code>True/False</code> entries for pairs that succeed and fail the condition we set:</p>

<pre><code>[False, True, False, False, False, True, False, True, False, False]
</code></pre>

<p>Here's where another built-in function comes in handy, <code>sum()</code>. You can supply <code>sum</code> with a list of values and it will sum these up to a single value; fortunately, in <code>Python</code>, <code>True</code> is treated as <code>1</code> so <code>sum</code> can easily sum it up and find a result if we supply the list we created previously:</p>

<pre><code>sum(i == 2 and j == 4 for i,j in zip(a, a[1:]))
</code></pre>

<p>Doing this helps us reach the final result of <code>3</code>.</p>

<p>In a procedural way this can be translated as:</p>

<pre><code>count = 0
for i,j in zip(a, a[1:]):
    if i == 2 and j == 4:
        count += 1
print(count)
</code></pre>

<p>This again yields <code>3</code> as does the <code>sum</code> solution.</p>

python python-3.x indexing