2 Types of Membership Operators in Python

2 Types of Membership Operators in Python

The 2 Types of Membership Operators in Python are used to check whether a value exists within a sequence like a list, tuple, string, or dictionary. Unlike comparison operators that evaluate equality, membership operators test for the presence or absence of an element, making them essential for efficient data checks and condition handling in Python programs.

There are two types of membership operators :

i. in operator

It returns true if a value or variable is member of a sequence.

Examples:

a. List

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("mango" in fruits) # False

b. Tuple

numbers = (1, 2, 3, 4, 5)
print(3 in numbers) # True
print(6 not in numbers) # True

b. Tuple

numbers = (1, 2, 3, 4, 5)

c. Set

c= {"red", "green", "blue"}
print("green" in colors# True
print("yellow" not in colors# Trueolors 


c. Set

colors = {“red”, “green”, “blue”}

d. String

word = “hello”
print(“h” in word) # True
print(“z” not in word) # True

d. String

word = “hello”

e. Python

student = {"name": "Alice", "age": 20}
print("name" in student) # True
print("Alice" in student) # False (checks keys, not values)
print("grade" not in student) # True

i. not in 

It returns true if two variables don’t refer to same value or same memory location.

Example:

str = ‘Ladder Python’
print(‘k’  not in str)

**It returns True as alphabet ‘k’ is not contained in string ‘Ladder Python

# Program to demonstrate Membership Operators

str = ‘Ladder Python’
list = [10,20,30,40]
dict1 = {1:’a’,2:’b’,3:’c’}
print(‘d’ in str)

# Output is True as alphabet ‘d’ is contained in ‘Ladder Python’

print(‘Tutorial’ not in str)

# Output is True as string value ‘Tutorial’ is not a part of Ladder Python’

print(10 in list)

# Output is True as 10 is contained in list

print(20 not in list)

# Output is false as 20 is contained in list

print(2 in dict1)

# Output is true as 2 is contained in dictionary dict1

Lesson tags: 2 Types of Membership Operators in Python, Membership Operators in Python, python operators
Back to: Python Programming