Membership Operators
Membership operators are tools that can helps us determine if a certain value is inside a list or string.
These membership operators are:
in
: evaluates toTrue
if it finds a value inside a sequence, otherwise, it will evaluate toFalse
.not in
: evaluates toTrue
if it doesn't find a value inside a sequence, otherwise, it will evaluate toFalse
.
Using Membership operators on lists
Using the in
membership operator
Let's assume a list of months:
months = ['January', 'February', 'April']
let's check if June
is inside this list:
print( 'June' in months )
>> False
Since June
is not inside months
, the boolean evaluation will be False
.
If I switch the value to January
:
print( 'January' in months )
>> True
The evaluation turns to True
, since January
is available inside the list months
.
Using the not in
membership operator
On the other hand, if you switch in
with not in
:
print( 'January' not in months )
>> False
it will evaluate to False
, since January
is available in the list.
Using Membership operators on strings
Using the in
membership operator
With membership operators, the same concept can be applied to strings, for example:
course = 'Python Crash Course' print( 'Crash' in course )
>> True
since the word crash
is available in the list of characters course
, the operation will evaluate to True
.
change the value to rash
print( 'rash' in course )
>> True
and it still evaluates to True
, this is because the set of characters in rash
are available in the string course
Now if we change the value to random characters:
print( 'frfr' in course )
>> False
Using the not in
membership operator
Using the not in
operator also works the same way as it did for lists. In this case:
print('frfr' not in course)
>> True
since frfr
is not available in the string course, we get an evaluation of True
.