Python Programming - Membership Operators

You can learn about Operators in Python Programs with Outputs helped you to understand the language better.

Python Programming – Membership Operators

Python has membership operators, which test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators explained below:

in Operator

Evaluates to true if it finds a variable in the specified sequence and false otherwise. For example, x in y; here, in results in a 1 if x is a member of sequence y.

not in Operator

Evaluates to true if it does not find a variable in the specified sequence and false otherwise. For example, x not in y. Here not in results in a 1 if x is not a member of sequence y.

Example 17.
Boolean test to find whether a value is inside a con-tainer or not:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
For strings, tests for substrings:
>>> a = ‘abode’
>>> ‘c’ in a
True
>>> ‘cd’ in a
True

Example 18.
Demo of working of Membership Operators.

From the python shell,enter the following and observe the results:

>>> 10 in (40, 20, 10)
True
>>> 10 not in (40, 20, 10)
False
>>> grade = ‘B+’
>>> grade in (‘A’, ‘A+’ ‘B’, ‘B+’, ‘C’, ‘C+’,’D’)
True
>>> >>> grade = ‘E’
>>> grade in (‘A’,’A+’, ‘B’, ‘B+’, ‘C’, ‘C+’,’D’)
False
>>>

Let’s Try

Write the output of following membership operators operations:

# Working with membership operators
>>> t = [2, 4, 6, 8]
>>> 3 in t
>>> 4 in t
>>> 4 not in t
# Working with membership operators
>>> a=’abode’
>>> b in a
>>> ‘b’ in a
>>> ‘ab’ in a
>>> ‘ac’ in a
>>> ‘de’ in a

Leave a Reply

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