Python Membership Operators
Membership Operators in Python
Membership operators are used to test whether a value or variable is found in a sequence (like a list, tuple, string, or dictionary). There are two membership operators in Python: in
and not in
.
List of Membership Operators
Operator | Description | Example |
---|---|---|
in | Returns True if the specified value is found in the given sequence | element in sequence |
not in | Returns True if the specified value is not found in the given sequence | element not in sequence |
Examples of Membership Operators
1. Using the in
Operator
The in
operator checks if a value exists in a sequence.
2. Using the not in
Operator
The not in
operator checks if a value does not exist in a sequence.
Examples with Other Data Types
1. Using Membership Operators with Tuples
2. Using Membership Operators with Dictionaries
When using in
with dictionaries, it checks for the presence of keys.
Summary of Membership Operators:
in
: ReturnsTrue
if the specified value is found in the sequence (list, tuple, string, or dictionary).not in
: ReturnsTrue
if the specified value is not found in the sequence.
Membership operators are very useful for quickly checking for the existence of elements within various data structures, making them essential tools for efficient coding in Python.