speedy
speedy

Reputation: 1

Comparing member of a list in Python

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 if x == a[i]: when a number is not in the list.

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"

Upvotes: 0

Views: 146

Answers (6)

Germán Ruelas
Germán Ruelas

Reputation: 125

You can also use a for loop to avoid the index error, try this

def is_member(x):

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

    for i in range(len(a)):
        if x == a[i]:
            return True
    return False

Upvotes: 2

sberry
sberry

Reputation: 132098

Try something like this instead:

def is_member(x):
    a = [1,5,3,9,4,100]
    for i in a:
        if i == x:
            return "True"
    return "False"

Here we iterate over a, and if any member == x we return "True" right away. If we have not returned by the end of the loop then the element is not present.

Upvotes: 1

be_good_do_good
be_good_do_good

Reputation: 4441

def is_member(x):

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

    while found == False:
        if i >= 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"

to handle end of list, a piece of code has been added

In fact you do not another variable like Found, you can do it in below way.

def is_member(x):

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

    while True:
        if i >= len(a):
            print 'test'
            return False # end of list reached
        if x == a[i]:
            return True
        i += 1

Upvotes: 1

user2963732
user2963732

Reputation: 21

That's because you are going outside the bounds of the list.

You should add a check so you can return when i > len(a).

Upvotes: 2

mengg
mengg

Reputation: 310

You need to add a condition that if (i == len(a)-1): return False. Because the index can not exceed the length of list a.

Upvotes: 1

freakish
freakish

Reputation: 56527

If there is no element in the list, then your i gets bigger and bigger until it becomes i = len(a). At this point a[i] throws an IndexError since you went above the list size. Simple fix would be to use while i < len(a): instead of while found == false: since you break the loop at x == a[i] anyway.

Upvotes: 2

Related Questions