Introduction

One of the important concepts in Python is the use of operators, which enable us to perform various operations on variables such as addition, subtraction, and multiplication. In Python, membership operators are used to test if a value or variable is found in a sequence like a list,  tuple, or dictionary. Therefore, this tutorial will provide a detailed explanation of membership operators and how they can be used in Python programming. By the end of this tutorial, you will have a good understanding of how to use membership operators to test for the presence of values in sequences in your Python programming projects.

Table of Contents :

  • What are membership operators in Python?
    • In membership operator 
    • Not In membership operator

What are membership operators in Python?

  • In Python membership operators are used to check if an object is a member of a sequence, such as string, list, tuple. 
  • In other words it checks whether an object is present in a given sequence or not. 
  • Membership operators return boolean values True or False depending on the presence of the object in sequence or not.
  • There are two membership operators in Python
    • in Operator
    • not in Operator

In membership operator :

  • It returns True if the object to be searched is present in the sequence. 
  • Otherwise, it returns False.
  • Code Sample :

x = 10
y = 100
ch = "F"
seq = [10, 20, 30]
str_seq = "ABCDEF"

res_x = x in seq
res_y = y in seq
res_ch = ch in str_seq

print(res_x)
print(res_y)
print(res_ch)

# Output
# True
# False
# True

Not In membership operator :

  • It returns True if the object to be searched is not present in the sequence. 
  • Otherwise, it returns False
  • Code Sample :

x = 10
y = 100
ch = "F"
seq = [10, 20, 30]
str_seq = "ABCDEF"

res_x = x not in seq
res_y = y not in seq
res_ch = ch not in str_seq

print(res_x)
print(res_y)
print(res_ch)

# Output
# False
# True
# False

Prev. Tutorial : Logical Operators

Next Tutorial : Identity operators