Using alphabet as counter in a loop
<p>I am looking for the most efficient way to count the number of letters in a list. I need something like</p>

<pre><code>word=[h e l l o]

for i in alphabet:
   for j in word:
      if j==i:
         ## do something
</code></pre>

<p>Where <em>alphabet</em> should be the <strong>spanish</strong> alphabet, that is the english alphabet including the special character <em>'Ã±'</em>.</p>

<p>I have thought about creating a list of pairs in the form of [[a, 0], [b,1], ...] but I suppose there is a more efficient/clean way.</p>

<p>It is not actually a dupe as you want to filter to only count characters from a certain set, you can use a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow">Counter</a> dict to do the counting  and a set of allowed characters to filter by:</p>

<pre><code>word = ["h", "e", "l", "l", "o"]

from collections import Counter
from string import ascii_lowercase

# create a set of the characters you want to count.
allowed = set(ascii_lowercase + 'Ã±')

# use a Counter dict to get the counts, only counting chars that are in the allowed set.
counts = Counter(s for s in word if s in allowed)
</code></pre>

<p>If you actually just want the total sum:</p>

<pre><code>total = sum(s in allowed for s in word)
</code></pre>

<p>Or using a functional approach:</p>

<pre><code>total = sum(1 for _ in filter(allowed.__contains__, word))
</code></pre>

<p>Using  <em>filter</em> is going to be a bit faster for any approach:</p>

<pre><code>In [31]: from collections import Counter
    ...: from string import ascii_lowercase, digits
    ...: from random import choice
    ...: 

In [32]: chars = [choice(digits+ascii_lowercase+'Ã±') for _ in range(100000)]

In [33]: timeit Counter(s for s in chars if s in allowed)

100 loops, best of 3: 36.8 ms per loop


In [34]: timeit Counter(filter(allowed.__contains__, chars))
10 loops, best of 3: 31.7 ms per loop

In [35]: timeit sum(s in allowed for s in chars)
10 loops, best of 3: 35.4 ms per loop

In [36]: timeit sum(1 for _ in filter(allowed.__contains__, chars))

100 loops, best of 3: 32 ms per loop
</code></pre>

<p>If you want a case insensitive match, use <em>ascii_letters</em> and add <code>'Ã±Ã'</code>:</p>

<pre><code>from string import ascii_letters

allowed = set(ascii_letters+ 'Ã±Ã')
</code></pre>

python list character