Kodeclik Blog

Python's not in Operator

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?
If you liked learning about the not in operator, checkout the Python hasattr() function.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.