in and not in Membership Operators# Basic membership check using 'in' and 'not in'
my_list = [3, 4, 5, 8, 3]
print(5 in my_list) # True
print(9 not in my_list) # True
x in my_iterable and x not in my_iterable The in operator returns True if the specified element is present in the sequence, and False otherwise. Conversely, the not in operator returns True if the element is not present. Both in and not in are reserved keywords in Python. For object identity comparisons, see is and not is, or check iterator states with Iterator and any().
| Operator | Description | Example |
|---|---|---|
in | Returns True if value is found in the sequence | 5 in [3, 4, 5] → True |
not in | Returns True if value is NOT found in the sequence | 9 not in [3, 4, 5] → True |
result = x in my_iterable
result = x not in my_iterable
Parameters: x is the target element to search for; my_iterable is any iterable data structure (list, tuple, string, set, dictionary keys, or generator).
Checking presence of elements inside a list:
my_list = [3, 4, 5, 8, 3]
if 5 in my_list:
print("Yes it is Present")
else:
print("NO it is NOT Present")
# Using not in
if 9 not in my_list:
print("Yes it is NOT Present")
Expected output
Yes it is Present
Yes it is NOT Present
Membership operators work seamlessly with strings to check for substrings or individual characters:
url = 'plus2net.com'
if '2' in url:
print("yes 2 is available inside")
else:
print("No 2 is not available inside")
assert ('net' in url) == True
Expected output
yes 2 is available inside
When used with a dictionary, in checks against the keys, not the values:
my_dict = {0: 'A', 1: 'B'}
print(1 in my_dict) # True (key 1 exists)
print('A' in my_dict) # False ('A' is a value, not a key)
my_dict2 = {'A': 'X', 'B': 'Y', 'C': 'Z'}
print('C' in my_dict2) # True
print('Y' not in my_dict2) # True (Y is a value)
my_tuple = (6, 1, 12, 7)
print(7 in my_tuple) # True
print(8 not in my_tuple) # True
assert (1 in my_tuple) == True
By default, the in operator checks only against dictionary keys. To check if a value exists, use value in my_dict.values().
For lists, tuples, and strings, the time complexity is O(n) because Python performs a linear search. For sets and dictionaries (when checking keys), the time complexity is O(1) on average due to hash table lookups.
Yes! not in is frequently used in conditional branches (if x not in my_list:) and filter comprehensions to ensure uniqueness or exclude unwanted items.
Test membership checks across lists, strings, dictionaries, and tuples in our interactive Google Colab companion notebook:
Launch the notebook directly in Google Colab to run live code cells or inspect the source repository on GitHub:
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.