Python Membership Operators

With the Python membership operators, we can check if an item exists in another item like a string, list, tuple, or dictionary. These operators are one of the Python operator types.





There are two operators:

  • IN: Returns true if the item exists, otherwise returns false.
  • NOT IN: Returns true if the item does not exist, otherwise returns false.

Let’s try some examples.

IN Operator

The IN operator returns True if the item exists. For example, we can check if a string exists in a string:

Or if a string exists in a list:

Or whether a number exists in a list:

Or if a certain key exists in a dictionary:

NOT IN Operator

The NOT IN operator returns True if an item doesn’t exist in another item. For example, we can check if a string doesn’t exist in another string:

Or whether a string doesn’t exist in a list:

Conclusion

You have learned how to use the IN and NOT IN membership operators to check whether an item exists in another item. I hope you enjoyed this lesson. If you have any questions, please leave a comment.


Ask a question or start a discussion by visiting our Community Forum