7. Membership Operators
Membership operators are used to check if a value is present in a sequence
(like string, list, tuple, set,
or dictionary). They return True if the value is found, otherwise
False.
These are mostly used in if or while conditions. In a dictionary, they check only for keys, not values.
Membership operators are useful for searching, validating data,
and filtering values. In case of strings, the check is
case-sensitive. For example, 'A' in 'apple' will return
False.
There are 2 types of Identity Operators in Python:
- in
- not in
List of Membership Operators
| Operator | Name | Description |
|---|---|---|
in |
Membership Operator | Returns True if the specified value is present in the sequence. |
not in |
Negative Membership | Returns True if the specified value is not present in
the sequence. |
Explanation in detail with example of types of Membership Operators:
-
Membership Operator (
in):The in operator checks if a value exists inside a sequence.
fruits = ["apple", "banana", "mango"] print("banana" in fruits) # TrueOutput:
TrueExplanation:
Here,
"banana"is present in the list calledfruits, so"banana" in fruitsreturns True. -
Negative Membership Operator (
not in):The not in operator checks if a value does not exist in a sequence.
colors = ["red", "green", "blue"] print("yellow" not in colors) # TrueOutput:
TrueExplanation:
Here,
"yellow"is not found in thecolorslist, so"yellow" not in colorsgives True.
Where it is Used?
- To check if an item exists in a list, string, tuple, set, etc.
- Commonly used in
ifstatements, loops, and filtering. - Helpful in checking presence or absence of values.
Example:
my_list = [1, 2, 3, 4, 5]
print(3 in my_list) # True
print(7 in my_list) # False
print(6 not in my_list) # True
print(2 not in my_list) # False
Explanation:
3 in my_list→ True because 3 is present in the list.7 in my_list→ False because 7 is not present.6 not in my_list→ True because 6 is missing from the list.2 not in my_list→ False because 2 exists in the list.
Note: These operators are most useful in conditions, filtering, and validating data from collections like lists, strings, and dictionaries.
Summary
in→ Checks if value is present in sequencenot in→ Checks if value is not present in sequence- Returns boolean values:
TrueorFalse - Useful in decision-making and filtering