Nearby lessons
36 of 159Python - Membership Operators
- Define membership operators and what they check
- Use the in operator to test for presence
- Use the not in operator to test for absence
- Apply membership operators to strings, lists, tuples, sets, and dictionaries
- Explain how membership works for dictionary keys
Introduction
Membership operators are used to check whether a value is present in a sequence or not.
The result of a membership operation is always a Boolean value:
TrueFalse
Membership Operators List
| Operator | Meaning |
|---|---|
in |
Returns True if the value is present. |
not in |
Returns True if the value is not present. |
Supported Data Types
Membership operators can be used with:
- Strings
- Lists
- Tuples
- Sets
- Dictionaries
1. in Operator
The in operator checks whether a value exists in a sequence.
Example - in Operator with String
Explanation
The character 'p' is present in the string, so the result is True.
The character 'z' is not present, so the result is False.
Example - in Operator with List
Example - in Operator with Tuple
Example - in Operator with Set
Example - in Operator with Dictionary
For dictionaries, membership operators check keys only.
Example - Dictionary Membership
Explanation
| Key | Value |
|---|---|
| 100 | durga |
| 200 | ravi |
The value 100 is a key, so the result is True.
The value "durga" is not a key; it is a value, so the result is False.
2. not in Operator
The not in operator checks whether a value is absent from a sequence.
Example - not in with String
Example - not in with List
Example - not in with Tuple
Example - not in with Set
Example - not in with Dictionary
Why is the Second Output True?
Dictionary membership operators check only keys.
Since "python" is a value and not a key, the result is True.
Membership Operators with User Input
Using Membership Operators in Conditions
Example - Using not in
Membership Operators with Strings
For strings, membership operators check whether a substring exists.
Example - String Membership
Real World Usage
Membership operators are commonly used in:
- Login systems
- Search operations
- Validation
- Filtering
- Permission checking
Example Areas
| Usage | Example |
|---|---|
| Login Validation | Username check |
| Search | Word search |
| Access Control | Permission validation |
Difference Between in and not in
| Operator | Meaning |
|---|---|
in |
Checks whether a value exists. |
not in |
Checks whether a value does not exist. |
- Membership operators check whether a value exists in a sequence
- in returns True when the value is present
- not in returns True when the value is absent
- The result of a membership operation is always True or False
- Dictionary membership operators check keys only
- For strings, membership operators check whether a substring exists