Python Membership Operators

Membership Operators are used to check if an element or item is present in the given collection or sequence.

Different Membership Operators

The following table presents the different membership operators in Python.

Operator Symbol Description Example
in Returns True if element (x) is present in sequence (y). x in y
not in Returns True if element (x) is not present in sequence (y). x not in y
Python Logical Operators

Examples

1 in Operator

In the following program, we check if an element e is present in the collection x.

main.py

e = 5
x = [0, 5, 10, 15, 20]

if e in x :
  print(f"{e} is present in {x}")
else:
  print(f"{e} is not present in {x}")

Output

5 is present in [0, 5, 10, 15, 20]

Let us rerun the above program with e = 12. Since, this value is not present in x, the expression e in x returns False.

main.py

e = 12
x = [0, 5, 10, 15, 20]

if e in x :
  print(f"{e} is present in {x}")
else:
  print(f"{e} is not present in {x}")

Output

5 is present in [0, 5, 10, 15, 20]

2 not in Operator

“not in” Operator is the inverse of the “in” operator.

In the following program, we check if an element e is not present in the collection x.

main.py

e = 12
x = [0, 5, 10, 15, 20]

if e not in x :
  print(f"{e} is not present in {x}")
else:
  print(f"{e} is present in {x}")

Output

12 is not present in [0, 5, 10, 15, 20]

Conclusion

In this Python Tutorial, we learned about Membership operators in Python, and how to use them with the help of example programs.