finding string in a list and return it index or -1
<p>Defining a procedure which return an index of item or -1 if the item not in list</p>

<pre><code>def ser(a,b):
    for j in a:
        if j == b:
            return (a.index(b))
        else:
            return -1

print (ser([1,2,3],3))
</code></pre>

<p>It's always return me -1. If i cut the 'else' part, it works. So why ?</p>

<p>That is because the first time you do not match the condition in your loop you immediately return and leave your method. You need to re-think your logic here to determine what it is you want to do when you don't match. Ultimately, you want to continue looping until you have exhausted your checks.</p>

<p>So, simply set your <code>return -1</code> outside of your loop. If you go through your entire loop, you have not found your match, so you can then return -1</p>

<pre><code>def ser(a,b):
    for j in a:
        if j == b:
            return (a.index(b))
    return -1

print (ser([1,2,3],3))
</code></pre>

<p>Alternatively, the loop can be avoided by using <a href="https://docs.python.org/3/reference/expressions.html#in" rel="nofollow">in</a>. So, you can actually re-write your method to this:</p>

<pre><code>def ser(a, b):
    if b in a:
        return a.index(b)
    return -1
</code></pre>

<p>You are checking to see if item <code>b</code> is in list <code>a</code>, if it is, return the index, otherwise return -1</p>

<p>To take the simplification further, you can actually set this in to a single line in your <code>return</code>:</p>

<pre><code>def ser(a, b):
    return a.index(b) if b in a else -1
</code></pre>

python list indexing