0

I am trying to test the existence of one of multiple values in an array and it isn't behaving as expected.

def valueInList(myList = "abcdefgh"):
    if "a" or "b" in myList:
        return True
    else:
        return False

For example:

>>> valueInList("abc") #should be True
True
>>> valueInList("def") #should be False
True

Why isn't this condition working?

  • I've added this as a catch-all for the many "why doesn't python understand human readable commands" questions I regularly see. –  Aug 07 '14 at 04:21
  • 1
    There was no need to make a new question, as this is probably the most common Python misconception and has numerous duplicates already. – Mark Ransom Aug 07 '14 at 04:37

1 Answers1

2

Python doesn't use natural language

While a person can understand "a" or "b" in myList the Python interpreter sees it very differently. Adding brackets helps to show this as the next two statements are equivalent:

"a"   or  "b" in myList
("a") or ("b" in myList)

As such, the condition will always return true as "a" is a Truthy value, that is it isn't False, 0, an empty string or an empty list.

Community
  • 1
  • 1