Search code examples
pythonmembership

List membership in Python without "in"


How to define 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 I should pretend Python did not have this operator.

This is what I've come up with, but it doesn't work!

def is_member(x, a):
   return x == a[::]

Solution

  • Recursive solution:

    def is_member(value, array):
        if len(array) == 0:
            return False
        return value == array[0] or is_member(value, array[1:])