Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Membership Operators

3.6.5

Membership Operators

Very often a program needs to ask a simple question about a collection: is this value inside it, or not? Membership operators answer exactly that. A membership operator is used to check whether a value is a member of a given sequence or not — the answer, as with relational and logical operators, is always True or False.

Python provides two membership operators, and they are opposites of each other.

The two membership operators

OperatorWhat it does
inReturns True if the variable or value is found in the specified sequence, and False otherwise
not inReturns True if the variable or value is not found in the specified sequence, and False otherwise

in at work

Take a list of numbers as the sequence:

>>> numSeq = [1, 2, 3]
>>> 2 in numSeq
True
>>> '1' in numSeq
False

The first check succeeds because the number 2 is genuinely one of the members of the list. The second check fails for a subtle but crucial reason: '1' (written in quotes) is a string, while numSeq contains the number 1. A string '1' and an integer 1 are different values of different data types, so the string is not found in the list and the result is False.

not in at work

not in asks the reverse question — is the value absent from the sequence?

>>> numSeq = [1, 2, 3]
>>> 10 not in numSeq
True
>>> 1 not in numSeq
False

10 does not appear anywhere in the list, so 10 not in numSeq is True. But 1 is a member of the list, so 1 not in numSeq is False.

Watch out

Membership checks respect data types. '1' in [1, 2, 3] is False because the quoted '1' is a string while the list holds the integer 1. When a membership test surprises you, check whether the value and the sequence's members are really of the same type. …

Table 3.7Membership operators in Python
OperatorDescriptionExample (Try in Lab)
inReturns True if the variable or value is found in the specified sequence and False otherwise>>> numSeq = [1,2,3]
>>> 2 in numSeq
True
>>> '1' in numSeq
False
#'1' is a string while
#numSeq contains number 1.