Membership Testing
When working with data structures, one of the most common questions is
"Does this value exist in this data structure?". Python comes to the rescue here with two
operators: in
and not in
.
Testing Membership in Sequences
Recall that the sequence types in Python are list
and tuples
. While
they can contain any data type, the order of the elements is guaranteed.
Testing membership using the in
and not in
operators combined with an
if
statement returns a truthy value
(boolean
) to indicate membership:
Testing Membership in a List | |
---|---|
Returns:
Using not in
works the opposite:
Negative Testing Membership in a List | |
---|---|
Would result in:
Testing Membership in Dictionaries
Dictionaries (the dict
data structure) present a little
bit of a special case in testing membership, the caveat being you must remember that by default,
the test runs against the key of the dictionary, not the entire key/value pair, nor against
the value itself.
Testing Membership in Dictionary Keys | |
---|---|
Would output:
If you'd like to test to see if a specific value is in a dictionary, remmember to use the
dict.values()
method:
Negative Testing Membership in Dictionary Values | |
---|---|
Which would return: