Membership operators in python



Introduction

Membership operators in python are used to check the presence of character or substring in the string, list, tuples, or in other data structures. There are two keywords to check the membership in python; in and not in keywords.

In

Returns True if it finds the specified character or substring in the sequence, False otherwise.

Example 1:

>>> name = 'Dawa penjor'
>>> 'Dawa' in name
True
>>> 'sonam' in name
False

Example 2:

name = "Dawa Penjor"
substring = str(input("Enter the substring to check for membership:")).title()
if substring in name:
    print(f"{substring} is a substring of {name}")

else:
    print(f"{substring} is not a substring of {name}")

Possible output:

# Check 1
Enter the substring to check for membership:dawa
Dawa is a substring of Dawa Penjor

# Check 2
Enter the substring to check for membership:penjor
Penjor is a substring of Dawa Penjor

# Check 3
Enter the substring to check for membership:sonam
Sonam is not a substring of Dawa Penjor

# Check 4
Enter the substring to check for membership:e
E is not a substring of Dawa Penjor

# Check 5
Enter the substring to check for membership:p
P is a substring of Dawa Penjor


Not in

Returns True if it does not finds the specified character or substring in the sequence, False otherwise.

Example 1:

>>> name = 'Dawa penjor'
>>> 'Dawa' not in name
False
>>> 'Sonam' not in name
True

Example 2:

name = "Dawa Penjor"
substring = str(input("Enter the substring to check for membership:")).title()
if substring not in name:
    print(f"{substring} is not a substring of {name}")

else:
    print(f"{substring} is a substring of {name}")

Possible output:

# Check 1
Enter the substring to check for membership:Dawa
Dawa is a substring of Dawa Penjor

# Check 2
Enter the substring to check for membership:sonam
Sonam is not a substring of Dawa Penjor

# Check 3
Enter the substring to check for membership:p
P is a substring of Dawa Penjor

# Check 4
Enter the substring to check for membership:pema
Pema is not a substring of Dawa Penjor

Check Edureka for more information about these operators in python.


Other operators in python you must know: