As the name indicates, “not in” is a logical operator in Python that returns true if a given object is not present in an iterable such as string, list, array, or dictionary. It returns False if the object is present.
Consider that we have a list of invitees to a party and we would like to check to see if specific people are invited. Here is a Python program to implement this:
Here are two sample runs:
As you can see 'not in' takes two inputs; in this case, x the user’s input and inviteelist, the iterable that contains the ground truth of who is invited to the party.
'not in' with strings
The “not in” operator works with many other iterables, e.g., strings. Consider:
The output is:
'not in' with dictionaries
The “not in” operator works with dictionaries too but note that the “not in” condition is applied to the keys of the dictionary, not to its values.
In the above code, we have a dictionary that represents our shopping cart. It contains the items we have and the number of entries of each item. We also have a grocerychecklist variable called “grocerynotes” which denotes the items we are supposed to purchase. Then a for loop is used to verify the presence of each item in the checklist in our shopping cart. In this manner, we notice that we have forgotten to purchase grapes.
Note that when we use “not in” with the shoppingcart dictionary variable, it is applied to the keys which are the names of vegetables, not the quantities (which are the values).
Using 'not in' with range
You can use “not in” with the range operator, like so:
Sample outputs are:
Note that we have to give one higher than 12 as the upper index for the range operator.
As you can see “not in” is a very convenient operator and leads to more readable code. How will you use it in your own programs?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.