in membership operator checks if a given value is part of a collection of values. Here's an example with
>>> num = 5 # checks if num is present among the integers 3 or 4 or 5 >>> num in range(3, 6) True
Instead of a series of
== comparisons combined with the
or boolean operator, you can utilize the
>>> pet = 'cat' # instead of doing this >>> pet == 'bat' or pet == 'cat' or pet == 'dog' True # use the membership operator >>> pet in ('bat', 'cat', 'dog') True
When applied to strings, the
in operator performs substring comparison.
>>> fruit = 'mango' >>> 'an' in fruit True >>> 'at' in fruit False
To invert the membership test, use the
not in operator.
>>> pet = 'parrot' >>> pet in ('bat', 'cat', 'dog') False >>> pet not in ('bat', 'cat', 'dog') True