Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Membership
Membership
Often the question is not where an element sits in a list but simply whether it is there at all. Python answers this with the membership operators, which test a list's contents and reply with a Boolean value — True or False.
The in operator
The membership operator in checks if the element is present in the list. It returns True when the element is found, else it returns False:
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
'Green' is one of the three elements, so the test succeeds; 'Cyan' is not, so it fails.
The not in operator
The operator not in is the transpose of in — it asks the opposite question. It returns True if the element is not present in the list, else it returns False:
>>> list1 = ['Red','Green','Blue']
>>> 'Cyan' not in list1
True
>>> 'Green' not in list1
False
The two operators always give opposite answers on the same test: whenever x in list1 is True, x not in list1 is False, and vice versa. Use whichever reads more naturally for the check you are making — asking "is it absent?" directly with not in is clearer than negating an in test yourself. …