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
.
Types of Identity Operators:
- 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. |
Types of Membership Operators
- in – Returns
True
if the value is found in the sequence. - not in – Returns
True
if the value is not found in the sequence.
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) # True
Output: True
Explanation:
Here,
"banana"
is present in the list calledfruits
, so"banana" in fruits
returns 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) # True
Output: True
Explanation:
Here,
"yellow"
is not found in thecolors
list, so"yellow" not in colors
gives True.
Where it is Used?
- To check if an item exists in a list, string, tuple, set, etc.
- Commonly used in
if
statements, 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:
True
orFalse
- Useful in decision-making and filtering