Membership Checks
Part of the Logic & Flow section of Coddy's Python journey — lesson 25 of 78.
Membership checks in Python let you check if a value exists in a collection like a list, tuple, set, or dictionary using in and not in.
The in operator checks if a value exists:
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # TrueThe not in operator checks if a value does not exist:
numbers = [1, 2, 3]
print(4 not in numbers) # TrueFor dictionaries, membership checks apply to keys by default:
my_dict = {"name": "Alice", "age": 25}
print("name" in my_dict) # True
print("Alice" in my_dict) # FalseChallenge
EasyYou are given a list of names and a dictionary of student grades. Write a program that:
- Check if "Alice" is in the list → Print:
"Alice is in the list." - Check if "David" is not in the list → Print:
"David is not in the list." - Check if "Bob" is in the dictionary → Print:
"Bob is in the dictionary." - Check if "Eve" is not in the dictionary → Print:
"Eve is not in the dictionary."
Cheat sheet
Use in and not in operators to check membership in collections:
Check if a value exists with in:
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # TrueCheck if a value does not exist with not in:
numbers = [1, 2, 3]
print(4 not in numbers) # TrueFor dictionaries, membership checks apply to keys by default:
my_dict = {"name": "Alice", "age": 25}
print("name" in my_dict) # True
print("Alice" in my_dict) # FalseTry it yourself
# Given data
names = ["Alice", "Bob", "Charlie"]
grades = {"Alice": 85, "Bob": 90, "Charlie": 78}
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter