2 types of Membership Operators in Python 3

2 types of Membership Operators in Python 3

Membership operators in Python are used to check whether a value or variable is member of a sequence (String, List, Tuple, Dictionary or set).

There are two types of membership operators :

Operator Description Example
in It returns true if a value or variable is member of a sequence. str = ‘Ladder Python’

print(‘d’ in str)

It returns True as alphabet ‘d’ is contained in string ‘Ladder Python’

not in
It returns true if two variables don’t refer to same value or same memory location. 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

 

Spread the love
Lesson tags: 2 types of Membership Operators in Python 3, in operator in python 3, not in operator in python 3
Back to: Python Programming Tutorial
Spread the love