Hello,
I've been trying to write a function 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. This is the script I could think of. I'm not even sure what might be wrong in this script! I find it tough studying Python :(
is_member(5, [5, 4, 3, 2]) returns True as expected. And every other trail also returns true! Please advise. Thanks.

def is_member(x,a):
  #x = 0
  a = [5, 4, 3, 2]   #wrong ! always returns true!
  try:
    a.index(x)
    return True
  except:
    return False

Hello Ram

Try doing it with while instead. If you are a newbee, make it so simple as it is does not bother a couple extra lines as long as you can follow the flow.

/Anders

def is_member(x,a):
    i = 0
    while i < len(a):
        if x == a[i]:
            return True
            i = i + 1
        else:
            i = i + 1

    return False

print is_member(5,[2,3,4,5])

Thanks Anders. That was simple :)

Another solution, using the any() builtin function

def is_member(x, a):
    return any(item == x for item in a)

Ooops! My great solution uses 'in' :). Fortunately, we have map()

def is_member(x, a):
    return any(map(lambda item: item == x, a))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.