Python tip 2: membership operator
The in
membership operator checks if a given value is part of a collection of values. Here's an example with range()
function:
>>> 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 in
operator.
>>> 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
Video demo:
See docs.python: Membership test operations for documentation. See also my 100 Page Python Intro ebook.