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>I think it will work (in python 3):</p>

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

def lastfirst(lst):
    for i in range(len(lst)-1):
        if lst[i][-1] != lst[i+1][0] :
            return lst[i+1]
    return None
print(lastfirst(lst))
</code></pre>

<p>Output:</p>

<pre><code>alba
</code></pre>

<blockquote>
  <p><strong>Explanation(Modifications needed in your code) :</strong></p>
  
  <ul>
  <li>We don't need two for loops we can do it in single for loop.</li>
  <li>Although you do increment <code>cont</code> variable in <code>else</code> statement but it will  always compare it with same string which is <code>a</code>.</li>
  </ul>
</blockquote>

<p>Another Input :</p>

<pre><code>lst = ['sky','you','use','ear','right']
</code></pre>

<p>Output: </p>

<pre><code>None
</code></pre>

<p>Hope it will help you.</p>

python list function for-loop