Can't get function to return false?

I'm working with this exercise:

Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)

I wrote this function:

def isMember(value, list):
  for element in list:
    if(element == value):
      return True
    else:
      return False

myList = ["a","b","c",1,2,3]

print(isMember("a",myList)) #Returns True; correct
print(isMember(3,myList)) #Returns False; why the heck?

Upvotes: 2

Views: 2728

Answers (2)

poke
poke

Reputation: 387667

The problem is that your return False is within the loop, directly as the else case of your membership test. So as you loop through the list, you get to the first element and check if it is in the list or not. If it is in the list, you return true—that’s fine. If it’s not in the list, you return false, aborting the loop process and ending the function. So you never look at the other values inside the loop.

So to fix this, move the return False outside of the loop, at the end of the function. That way, only when all elements have been looked at, you return false.

def isMember (value, list):
    for element in list:
        if element == value:
            return True
    return False

Another way would be to simplify this using the any function to perform the check for every element in the list. any takes an iterable and looks at the values. As soon as it finds a true value, it returns true. Otherwise it keeps iterating until it finds a false value or hits the end of the iterator, both cases yielding a false. So you could rewrite it like this:

def isMember (value, list):
    return any(value == element for element in list)

Upvotes: 3

mdml
mdml

Reputation: 22882

You need to take the return False out of the loop:

def isMember(value, list):
    for element in list:
        if(element == value):
            return True
    return False

The way you have it currently, isMember will return False if the value is not the first item in the list. Also, you should change the name of your list variable to something other than list, which is a built-in function in Python.

Upvotes: 11

Related Questions