Python Membership Operators


Introduction to Python Membership Operators

Membership operators are used to check if a variable is present in the sequence like string, list or tuple.

Note: It will work only for sequences, if you try to make it work for data types like integers, it will not work.

OperatorExampleDescription
ina in bReturns True if the variable is present in the sequence, else False.
not ina not in bReturns True if the variable is not present in the sequence, else False.

Membership Operators

in Operator

in Operator returns True if the specified variable or value is present in the sequence. It can be any sequence like a string, list, or tuple. If the value is not present in the sequence, then it will return False.

In [1]:
name = "logical"

print("logi" in name)
True
In [2]:
name = ["Logical", "Python"]

print("Logical" in name)
True
In [3]:
name = ["Logical", "Python"]

print("Learn" in name)
False

not in Operator

not in Operator returns True if the specified variable or value is not present in the sequence. If the value is present in the sequence, then it will return True.

In [1]:
name = "logical"

print("logi" not in name)
False
In [2]:
name = ["Logical", "Python"]

print("Logical" not in name)
False
In [3]:
name = ["Logical", "Python"]

print("Learn" not in name)
True

Resources

Handwritten Notes

References

  1. Membership operators
  2. PYTHON MEMBERSHIP AND IDENTITY OPERATORS
  3. Membership and identity operators