Testing for Membership
00:00
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.
00:12
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.
00:41
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,
00:59
"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"]
.
01:20
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.
01:39
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
02:04
and not outside that range, but that 50
is outside that range.
02:26
Next, you’ll see how the not
operator can be used when checking object identity.
Become a Member to join the conversation.