Testing for Membership
Now that you know how and where to use the
not operator, let’s look at some best practices for using it in Python, starting with membership.
Consider you want to determine if an item is in a particular collection or not. In Python, you use the
in operator to do that. So if you create a list of numbers, you can see that
3 is in it, and
5 is not.
If you want to return
True when something is not in a collection and
False when it is, use the
not operator in this way,
"c" is in that list, so to ask if it is not in that list will return
False. Note that it’s preferred in Python to type
"c" not in
["a", "b", "c"] instead of
not "c" in ["a", "b", "c"].
Here’s another example of membership based on something you saw before. Recall using
and to see if a number was in a particular range. But Python has a
range() function to generate the collection of integers in a range. So you can use the
in operator to test for that.
So now, if you want to test if a number is outside that range, you can use the
not operator. Using values you’ve seen before, you can now check that
30 is in that range
and not outside that range, but that
50 is outside that range.
Next, you’ll see how the
not operator can be used when checking object identity.
Become a Member to join the conversation.