Computer Science · Ch 9 — Lists
Membership
9.2.3
Membership
Just as with strings, Python provides membership operators to ask whether a value occurs in a list. There are two of them, and each returns a Boolean result — True or False.
The in operator
element in list checks whether the element is present in the list. It returns True if it is, and False otherwise:
>>> gases = ['Oxygen', 'Nitrogen', 'Argon']
>>> 'Nitrogen' in gases
True
>>> 'Helium' in gases
False
The not in operator
element not in list is the exact opposite test: it returns True when the element is absent from the list, and False when the element is present:
>>> gases = ['Oxygen', 'Nitrogen', 'Argon']
>>> 'Helium' not in gases
True
>>> 'Nitrogen' not in gases
False
Key points
in→Trueif the value is an element of the list, elseFalse.not in→Trueif the value is not an element of the list, elseFalse. …