jacobMorritz
jacobMorritz

Reputation: 13

checking whether a string exists in a list

I am simply trying to figure out why the simple code below does not return anything back even though Im almost positive i am correct:

mike = [1,2,3,3,"error"]

if "error" in mike == True:
    print(True)

this returns nothing. Why?

Upvotes: 1

Views: 31

Answers (2)

a_guest
a_guest

Reputation: 36249

This is a result of operator chaining which works for the comparison operators in, not in, is, is not, <, <=, >, >=, !=, ==. So

'error' in mike == True

is actually evaluated as:

'error' in mike and mike == True

the latter of which is false. Operator chaining is more useful for things like 0 < x < 5.

You want probably just

'error' in mike

Upvotes: 3

G. Anderson
G. Anderson

Reputation: 5955

You can force evaluation in the order you want with parentheses:

if ("error" in mike) ==True:
    print(True)

or, more pythonically:

if "error" in mike:
    print(True)

Upvotes: 2

Related Questions