21
NovPython Membership Operators: Types of Membership Operators
Membership Operators in Python
Membership operators in Python check and evaluate the presence of a value in a collection or sequence. In other words, the membership operators in Python checks whether an item is a member of the given collection. The collection or sequence can be strings, lists, or tuples. This type of check is known as the membership test.
In this Python tutorial, we'll study the types of membership operators in Python with examples.
Before proceeding forward, you must be thorough with the following topics in Python:
Types of Python Membership Operators
There are two types of membership operators in Python: They are:
Operator Name | Description |
in Operator | returns true if the value is present in the sequence |
not in Operator | returns true if the value is not present in the sequence |
1. Python 'in' Operator
The "in" operator checks whether a substring is present in a more extensive string, an item or element is present in a list, tuple, dictionary, or set, or a sub-list or sub-tuple is included in a list or tuple.
Example of 'in' Operator in Python
list1 = [18, 82, 36, 24, 52]
str1 = "Welcome to ScholarHat"
set1 = {11, 28, 73, 94, 85}
dict = {1: "Hello", 2:"everyone", 3:"scholarhat"}
tup = (1, 2, 93, 44, 55)
# checking an integer in a list
print(36 in list1)
# checking a character in a string
print('m' in str1)
# checking an integer in a set
print(73 in set1)
# checking for a key in a dictionary
print(3 in dict)
# checking for an integer in a tuple
print(39 in tup)
In the above example, the 'in' operator checks whether the value is present in a list, string, st, dictionary, or tuple.
Read More: Top 50+ Python Interview Questions and Answers |
Output
True
True
True
True
False
2. Python ‘not in’ Operator
The “not in” operator is the inverse of the “in” operator. It returns true if a substring is not present in a more extensive string, an item or element is absent in a list, tuple, dictionary, or set, or a sub-list or sub-tuple is not included in a list or tuple.
Example of 'not in' Operator in Python
list1 = [19, 62, 53, 40, 52, 34]
str1 = "Hello ScholarHat"
set1 = {10, 22, 73, 41, 5}
dict1 = {1: "Welcome", 2:"to", 3:"ScholarHat"}
tup1 = (1, 2, 3, 4, 5)
# checking an integer in a list
print(25 not in list1)
# checking a character in a string
print('O' not in str1)
# checking an integer in aset
print(5 not in set1)
# checking for a key in a dictionary
print(3 not in dict1)
# checking for an integer in a tuple
print(90 not in tup1)
In the above example, the 'not in' operator checks whether the value is present in a list, string, st, dictionary, or tuple.
Output
True
True
False
False
True
Also, explore the following Python operators: |