Membership operators help you check if something is inside a group or not. They make it easy to find out if a value exists in a list, string, or other collections.
0
0
Membership operators (in, not in) in Python
Introduction
Checking if a name is in a list of invited guests before allowing entry.
Finding out if a word contains a certain letter.
Verifying if a key exists in a dictionary before using it.
Seeing if a number is part of a set of allowed values.
Syntax
Python
value in collection value not in collection
in returns True if the value is found inside the collection.
not in returns True if the value is NOT found inside the collection.
Examples
Checks if 5 is in the list. Result is True.
Python
5 in [1, 2, 3, 4, 5]
Checks if letter 'a' is NOT in the string 'hello'. Result is False.
Python
'a' not in 'hello'
Checks if 'key' is a key in the dictionary. Result is True.
Python
'key' in {'key': 10, 'other': 20}
Sample Program
This program checks if 'banana' is in the fruits list and prints a message. Then it checks if 'orange' is not in the list and prints another message.
Python
fruits = ['apple', 'banana', 'cherry'] # Check if 'banana' is in the list if 'banana' in fruits: print('Banana is in the list!') # Check if 'orange' is not in the list if 'orange' not in fruits: print('Orange is not in the list!')
OutputSuccess
Important Notes
Membership operators work with many types like lists, strings, tuples, sets, and dictionaries (checks keys).
They return True or False, so you can use them directly in conditions.
Summary
in checks if a value is inside a collection.
not in checks if a value is NOT inside a collection.
Use them to write clear and simple checks for membership.