Python Membership Operators
Table of Contents
Description
Membership operators are used to test whether a value exists in a sequence (like string, list, tuple, set, or dictionary). These operators return True or False.
Python provides two membership operators:
Operator Description Example Result
in Returns True if value is present 'a' in 'apple' True
not in Returns True if value is not present 'z' not in 'apple' True
Prerequisites
- Understanding of sequences (list, string, tuple, etc.).
- Familiarity with Boolean expressions.
Examples
Here's a simple program in Python:
# String membership print('a' in 'apple') # True print('z' in 'apple') # False # List membership fruits = ['apple', 'banana', 'cherry'] print('banana' in fruits) # True print('grape' not in fruits) # True # Tuple membership numbers = (1, 2, 3) print(2 in numbers) # True # Dictionary key membership data = {'name': 'Ravi', 'age': 21} print('name' in data) # True # Only keys are checked print('Ravi' in data) # FalseReal-World Applications
Login systems: Check if a username exists in a database.
Chatbots: Check if a keyword is in a user’s input.
Search features: Filter based on inclusion of keywords.
Security systems: Validate if a user or device is in an authorized list.
Data analysis: Validate if a value exists in a dataset or column.
Where topic Can Be Applied
Conditional checks: Search within strings, lists, etc.
Form validation: Check selected values.
Web development: Validate inputs, route checks.
Machine learning: Check if feature exists in the dataset.
Data pipelines: Confirm presence of keys/columns.
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What does the in operator do in Python?
How does in work with dictionaries?
Can in be used with sets and tuples?
What is the result of 'key' in dict if the key exists?
What will 'value' in dict return if 'value' is only a value and not a key?