Python “in” and “not in” Membership Operators

Filed Under: Python
Python In And Not In Operators

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:

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.

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')
Python In Operator Example 1
Python in Operator Example

Recommended Readings: Python input(), Python List

We can use the “in” operator with Strings and Tuples too because they are sequences.

>>> 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.

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.

>>> primes=(2,3,5,7,11)
>>> 6 not in primes
True
>>> 3 not in primes
False

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages