Table of Contents
Toggle
Python membership operators (in and not in) are essential tools for checking item existence in sequence types. They help determine if an element exists in:
text = "PythonProgramming"
print('Python' in text) # True
print('python' in text) # False (case-sensitive)
numbers = [10, 20, 30, 40]
print(25 in numbers) # False
print(30 in numbers) # True
Key Insight: The in operator checks for exact matches and is case-sensitive in strings.
languages = {'Python', 'Java', 'C++'}
print('Ruby' not in languages) # True
user = {'name': 'Alice', 'age': 30}
print('email' not in user) # True (checks keys only)
Pro Tip: With dictionaries, in only checks keys, not values.
coordinates = ( (10,20), (30,40) )
print((10,20) in coordinates) # True
print(10 in coordinates) # False
mixed_list = [10, 20.0, '30']
print(20 in mixed_list) # False (20 vs 20.0)
print('20' in mixed_list) # False
| Data Type | Time Complexity |
|---|---|
| List/Tuple | O(n) |
| Set/Dict | O(1) |
Optimization Tip: Use sets for membership checks when working with large datasets.
in and not in return boolean valuesPro Tip: Combine membership operators with conditional statements for powerful data validation in your Python programs.
