Python has two membership operators – “in” and “not in”. They are used to check if an element is present in a sequence or not.
Python in Operator
This operator returns True if the specified element is present in the sequence. The syntax of “in” operator is:
1 |
x in y |
Here “x” is the element and “y” is the sequence where membership is being checked.
Here is a simple program to show the usage of Python in operator.
1 2 3 4 5 6 7 |
vowels = ['A', 'E', 'I', 'O', 'U'] ch = input('Please Enter a Capital Letter:n') if ch in vowels: print('You entered a vowel character') else: print('You entered a consonants character') <img class="alignnone wp-image-28316 size-full" src="http://all-learning.com/wp-content/uploads/2020/04/Python-quotinquot-and-quotnot-inquot.png" alt="Python "in" and "not in&quot" width="1200" height="628" /> |
Recommended Readings: Python input(), Python List
We can use the “in” operator with Strings and Tuples too because they are sequences.
1 2 3 4 5 6 7 8 9 10 |
>>> name="JournalDev" >>> 'D' in name True >>> 'x' in name False >>> primes=(2,3,5,7,11) >>> 3 in primes True >>> 6 in primes False |
Can we use Python “in” Operator with Dictionary?
Let’s see what happens when we use “in” operator with a dictionary.
1 2 3 |
dict1 = {"name": "Pankaj", "id": 1} print("name" in dict1) # True print("Pankaj" in dict1) # False |
It looks like the Python “in” operator looks for the element in the dictionary keys.
Python “not in” Operator
It’s opposite of the “in” operator. We can use it with sequence and iterables.
1 2 3 4 5 |
>>> primes=(2,3,5,7,11) >>> 6 not in primes True >>> 3 not in primes False |