Python’s membership operators evaluate whether or not a variable exists in a specified sequence. There are two membership operators, as shown in the table that follows
|
Membership Operator |
Description |
|
in |
It evaluates to true if it finds a value in the specified sequence; it evaluates to false otherwise. |
|
not in |
It evaluates to true if it does not find a value in the specified sequence; it evaluates to false otherwise. |
Next are some examples of Boolean expressions that use membership operators.
x in [3, 5, 9]. This can be read as “test if x is equal to 3, or equal to 5, or equal to 9”. It can be written equivalently as
x == 3 or x == 5 or x == 9
s in "ace". This can be read as “test if the content of variablesappears in the word “ace” or in other words, test ifsis equal to letter “a”, or equal to letter “c”, or equal to letter “e”, or equal to word “ac”, or equal to word “ce”, or equal to word “ace”. It can be written equivalently as
s == "a" or s == "c" or s == "e" or s == "ac" or s == "ce" or s == "ace"
Notice: Please note that the Boolean expression
s in "ace"does not check whether or notsis equal to “ae”. It only checks for the presence of the content of variableswithin the specified sequence of letters in the word “ace”.
s not in ["a", "b"]. This can be read as “test ifxis not equal to letter “a”, nor equal to letter “b”. It can be written equivalently as
not(s == "a" or s == "b")
or as
s != "a" and s != "b"