Python exercise: last letter / first letter
<p>I'm a newbie Python student and I'm going through some simple (but now, for me, complicated) exercises. I tried in many ways, but I decided to stop guessing, because I believe it won't be a sane routine of learning.</p>

<p>I have to solve the following exercise:</p>

<blockquote>
  <p>Write a <code>lastfirst(lst)</code> function, that, given a list, returns the
  first word in the list that starts with a different character from the
  last character of the previous word. If there isn't such a word,
  return <code>None</code>.</p>
  
  <p>Example:</p>
  
  <p><code>lst = ['sole','elmo','orco','alba','asta']</code> returns <code>'alba'</code></p>
  
  <p><code>lst = ['sky','you','use','ear','right']</code> returns <code>None</code></p>
</blockquote>

<p>I've tried to solve it, and what I had is this:</p>

<pre><code>lst = ['sole','elmo','orco','alba','asta']

def lastfirst(lst):

    cont = 0
    d = 1 
    for a in lst[cont:]: 
        for b in lst[d:]:       
            if a[-1] != b[0]:
                return lst[d]
            else:
                 cont = cont + 1   
                 d = d + 1  

print(lastfirst(lst))
</code></pre>

<p>The problem I detected is:</p>

<p>The program doesn't make a distinction between taking the first letter of the first word and the last letter of the second word, or the last letter of the first word and the first letter of the second word.</p>

<p>PS: Sorry for my English :)</p>

<p>Here's a solution using itertools.</p>

<p>First, define a function that returns a boolean if your condition is met:</p>

<pre><code>def check_letters(apair):
"In a pair, check last letter of first entry with first letter of second"
    return apair[0][-1] == apair[1][0]
</code></pre>

<p>Now we use the pairwise function from the <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code> module</a> recipes:</p>

<pre><code>import itertools
def pairwise(iterable):
    "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)
</code></pre>

<p>And finally:</p>

<pre><code>lst = ['sole','elmo','orco','alba','asta']
lstlast = [item[1] for item in pairwise(lst) if not check_letters(item)]
# returns ['alba']
</code></pre>

python list function for-loop