Comparing member of a list in Python
<p>I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line <code>if x == a[i]:</code> when a number is not in the list.</p>

<pre><code>def is_member(x):

    a = [1,5,3,9,4,100]
    i = 0
    found = False

    while found == False:
        if x == a[i]:
            found = True
            break
        i += 1
    if found == True:
        return "True"
    else:
        return "False"
</code></pre>

<pre><code>def is_member(x):

    a = [1,5,3,9,4,100]
    i = 0
    found = False

    while found == False:
        if i &gt;= len(a):
            return False # end of list reached
        if x == a[i]:
            found = True
            break
        i += 1
    if found == True:
        return "True"
    else:
        return "False"
</code></pre>

<p>to handle end of list, a piece of code has been added</p>

<p>In fact you do not another variable like <code>Found</code>, you can do it in below way.</p>

<pre><code>def is_member(x):

    a = [1,5,3,9,4,100]
    i = 0

    while True:
        if i &gt;= len(a):
            print 'test'
            return False # end of list reached
        if x == a[i]:
            return True
        i += 1
</code></pre>

python