Python - Membership Operators

Python

Share
python logo

In this tutorial we will learn about Membership operators in Python.

We use the membership operator to check the membership of an item in a given sequence like tuple, list or string.

Following are the membership operators in Python

The in operator

This operator returns True if a given item is in the sequence. Otherwise, it returns False.

Example #1

In the following example we have a string "The quick brown fox jumps over the lazy dog." and we are checking if the string "fox" is in the string using the in operator.

haystack = "The quick brown fox jumps over the lazy dog."
needle = "fox"

result = needle in haystack

print("result:", result)

We will get True because the word "fox" is in the given string.

Example #2

In the following example we have a list and we are checking if the value 10 is in the list using the in operator.

haystack = [1, 15, 10, 5, -99, 100]
needle = 10

result = needle in haystack

print("result:", result)

We will get True because 10 is present in the list.

The not in operator

This operator returns True if a given item is not in the sequence. Otherwise, it returns False.

Example #1

In the following example we have a string "The quick brown fox jumps over the lazy dog." and we are checking if the string "doe" is not in the string using the not in operator.

haystack = "The quick brown fox jumps over the lazy dog."
needle = "doe"

result = needle not in haystack

print("result:", result)

We will get True because the word "doe" is not in the given string.

Example #2

In the following example we are checking if 'Hello' is not in the given tuple using the not in operator.

haystack = ('Yusuf Shakeel', 9.1, True)
needle = "Hello"

result = needle not in haystack

print("result:", result)

We will get True because "Hello" is not present in the tuple.

Share