Table of Contents
Membership operators in
and not in
are essential in Python when you need to check whether a value exists within a container — such as a list, string,
tuple, dictionary, or set. These operators return a boolean value based on the presence (or absence) of an element. Whether you're validating user input, searching for keys in a
dictionary, or parsing text, you'll encounter membership checks regularly.
These practice tasks will help you become fluent in using in
and not in
with different data types and structures. You will also learn how to combine
membership operators with if
conditions, loops, and string manipulation.
Before solving the tasks, review the following topics to make sure you understand how membership works across Python’s core types:
- Membership Operators in Python
- Sequence Types (lists, tuples, and strings)
- Set Type in Python
- Mapping Type (Dictionaries)
- Boolean Type (how membership expressions evaluate)
- Basic
if
statements and Python syntax
Beginner-Level Practice - Membership Operators in Python
These beginner-level tasks focus on helping you understand how in
and not in
work with strings, lists, and basic containers. You'll get comfortable
writing conditions that check if certain values exist or are missing. These types of checks are everywhere in real-world Python code — from filtering user inputs to validating
form data or checking access rights. By solving these exercises, you’ll practice not only syntax but also your logical thinking and attention to data structures.
Task 1: Email Domain Check
Write a program that asks the user to enter their email address. Then check if the domain (the part after "@") is in a list of allowed domains. If it is, print "Domain
accepted", otherwise print "Domain not allowed". The valid domains are: gmail.com
, yahoo.com
, and outlook.com
.
What this Task Teaches
This task teaches you how to extract substrings from user input, how to compare them against a list, and how to use the in
operator to perform membership checks.
It's a common real-world scenario for filtering or validating inputs in web applications or system scripts.
Hints and Tips
You’ll need to split the email string at the "@" symbol and check the second part. Lists are a great way to hold your allowed domains.
- Use
input()
to ask for an email - Split the email using
.split("@")
- Create a list of allowed domains
- Use
if domain in allowed_list
to check membership
Common Mistakes
- Not splitting the email correctly: Some users forget to handle cases where the email is malformed or doesn't include "@", which can cause errors when trying to split the string.
- Case sensitivity: If the user enters "GMAIL.COM", your program may reject it if your list is in lowercase only. Normalize the input to lowercase.
-
Using
==
instead ofin
: Some mistakenly writeif domain == allowed_domains
, comparing to the entire list. - Including spaces: Extra spaces can be introduced when copying and pasting — use
.strip()
to clean input. - Empty or missing input: Always make sure to handle unexpected or missing input gracefully.
Step-by-Step Thinking
Think like a backend developer validating a user’s email. You need to isolate the domain and then validate it against a known list.
- Prompt the user to enter their email
- Use
.split("@")
to separate the name and domain - Check that the list has two parts
- Create a list of allowed domains
- Use
if domain in allowed_domains
to validate - Print an appropriate message
How to Make it Harder
- Support multiple emails in one input, separated by commas
- Normalize user input to ignore case and spaces
- Allow subdomains like
mail.google.com
to be accepted
Task 2: Keyword Alert
Create a script that asks the user to type a sentence. Check if the sentence contains any of the banned words: ["hack", "spam", "phish"]
. If any banned word is
found, print "Warning: inappropriate content detected!". Otherwise, print "Input is clean."
What this Task Teaches
This task reinforces how to scan user input for keywords using the in
operator inside a loop or a condition. You’ll practice searching strings for matches, which
is useful in content moderation, filtering, or alert systems. You'll also work with lists, string methods, and case normalization.
Hints and Tips
You’ll want to lowercase the user’s sentence before comparing it to your banned keywords list. Loop through the keywords and check if any are in the sentence.
- Use
.lower()
on the sentence to handle case-insensitive checks - Use a loop or
any()
to check each keyword - Print a warning message if a match is found
- Use
not in
to confirm the sentence is clean
Common Mistakes
- Checking full sentences against a list: Some try to match the entire sentence with a keyword list, which always fails. Check each word in the sentence instead.
- Not converting to lowercase: Without this, "Spam" won’t match "spam" in your list.
-
Missing partial matches: Consider how "phishing" might or might not be caught by "phish". You may need
in
checks, not just whole-word matches. - Improper use of loops: Beginners sometimes exit the loop early or don’t use
break
after a match. - Forgetting to strip input: Always clean up whitespace to avoid false negatives.
Step-by-Step Thinking
Imagine you're building a message filter. You want to detect whether a user’s sentence includes inappropriate words and raise an alert accordingly.
- Prompt the user to type a sentence
- Convert the sentence to lowercase
- Define a list of banned keywords
- Use a loop or
any()
to check for presence - If a match is found, print a warning
- If none found, print a confirmation
How to Make it Harder
- Count how many banned keywords were found and display the number
- Highlight the banned words in the original sentence
- Filter out punctuation before checking
Intermediate-Level Practice - Membership Operators in Python
These intermediate-level exercises focus on using membership operators with more complex data structures like dictionaries, nested lists, and user-generated input. You’ll explore
how in
and not in
behave when dealing with keys vs. values, checking presence within multiple layers, and working with formatted data. Mastering these
use cases will prepare you for real-world programming, where data validation and intelligent branching are key to building reliable Python applications.
Task 1: Check Ingredient Availability
You’re building a simple grocery assistant. The user inputs a list of ingredients they currently have (e.g., "eggs, milk, butter"). Then the program checks whether all required
ingredients for making pancakes — ["flour", "milk", "eggs"]
— are present. If all are available, print "You can make pancakes!", otherwise print "Missing
ingredients!".
What this Task Teaches
This task strengthens your ability to work with lists, clean up user input, and use in
in combination with all()
and loops. It introduces real-world
thinking about inventory validation and forces attention to formatting, splitting, and membership-based decisions — all crucial for building utility programs.
Hints and Tips
Make sure to split the input by commas and trim whitespace. Use the all()
function with a loop to check whether each required item is in the user’s list.
- Use
input()
and.split(",")
to parse the list - Use
.strip()
to remove extra spaces - Create a list of required ingredients
- Use
all(item in user_list for item in required)
Common Mistakes
- Forgetting to strip spaces: " eggs" won’t match "eggs". This leads to false negatives unless you use
.strip()
. - Comparing lists directly: Trying
if required in user_list
compares entire lists, which is incorrect. Useall()
instead. - Wrong data types: Sometimes users mistakenly turn the list into a string, which breaks
in
logic. - Partial match issues: "egg" won’t match "eggs". Encourage exact matching to avoid confusion.
- Case sensitivity: “Milk” and “milk” are not equal. Use
.lower()
to normalize input.
Step-by-Step Thinking
Think like a recipe checker: you know what’s required and you want to confirm whether all those ingredients are available. You’ll need to clean and validate user input.
- Ask the user to enter the list of ingredients
- Split the string by commas and strip whitespace
- Lowercase all items to match consistently
- Compare each required ingredient using
in
- Use
all()
to confirm all are present - Print the appropriate message
How to Make it Harder
- Display exactly which ingredients are missing
- Support ingredient aliases like "eggs" or "egg"
- Allow case-insensitive matching and fuzzy comparison
Task 2: Validate Login Permissions
A system contains a dictionary where usernames are keys and access levels are values. Ask the user to enter a username and check whether that user exists in the dictionary. If the username is not in the dictionary, print "Access denied." If the username exists and the access level is "admin", print "Welcome, admin!". Otherwise, print "Welcome, user."
What this Task Teaches
This task focuses on using in
with dictionaries and conditionals. You’ll learn the difference between checking keys and values, and how to combine multiple checks
to write smarter logic. This reflects a common use case in authentication, permissions, and role-based systems.
Hints and Tips
You need to check if the username exists in the dictionary keys. Use if username in users
and then access the corresponding value.
- Define a dictionary with usernames as keys and roles as values
- Use
input()
to get the username - Check if it exists using
in
- Access the value to determine their role
Common Mistakes
-
Checking values instead of keys: Many beginners mistakenly write
if username in users.values()
, which searches roles instead of usernames. - Case sensitivity: "Admin" and "admin" are different in Python. Always normalize input and dictionary values.
- Accessing a key without checking: Trying to retrieve
users[username]
without first checking existence may throw a KeyError. - Hardcoding messages: Beginners often duplicate logic instead of using
elif
conditions. - Forgetting to strip input: Extra spaces can lead to false mismatches.
Step-by-Step Thinking
You need to validate both the existence and the permission level of a username. Think like a system admin verifying login roles.
- Define a dictionary with usernames and access levels
- Ask the user to input a username
- Use
in
to verify the key exists - If found, check if their role is "admin"
- Display a personalized message accordingly
- If not found, deny access
How to Make it Harder
- Support case-insensitive matching for usernames
- Allow partial username matching using
in
across keys - Log each login attempt with time and result
Advanced-Level Practice - Membership Operators in Python
In these advanced-level challenges, you will apply in
and not in
to handle dynamic data structures, nested conditions, and real-world logic such as
access control and data validation. You'll also combine membership checks with string parsing, set operations, and custom logic in your own functions. These tasks are designed to
stretch your understanding of Python's membership model and teach you to think more critically about how data is structured and checked.
Task 1: Access Control with Nested Groups
A system uses nested groups to define access permissions. Each user belongs to a group, and each group has a list of resources it can access. Write a program that asks for the
user's group and a resource name, and tells the user whether they have access. For example, the group editors
can access
["articles", "drafts", "comments"]
, while admins
can access everything. If the group or resource doesn’t exist, print an appropriate message.
What this Task Teaches
This task pushes you to work with nested structures (dictionary of lists) and use in
and not in
inside conditionals. It models a real-world permission
system and emphasizes validating user input, safe dictionary access, and logical branching based on membership results.
Hints and Tips
Use a dictionary where keys are group names and values are lists of allowed resources. Remember to lowercase inputs and check for group presence before accessing its list.
- Use
in
to check group existence in the dictionary - Use
in
again to check resource inside the group’s list - Validate input with
strip()
andlower()
- Print clear messages for all possible outcomes
Common Mistakes
-
Accessing the group without checking its existence: Attempting to access a non-existing group directly with
groups[group]
can raise a KeyError. - Assuming all groups have the same resources: Beginners may hardcode logic without considering group differences.
-
Incorrect nesting of
in
checks: Misplacing checks can lead to incorrect access decisions. - Improper use of case: Group and resource names should be normalized using
lower()
. - Forgetting to handle unknown groups: Always confirm a group is valid before accessing it.
Step-by-Step Thinking
Imagine you're building a role-based access system. You must check if the group exists and whether the requested resource is in the group’s permissions.
- Create a dictionary of groups and their resource lists
- Ask for user input: group name and resource name
- Normalize input (trim spaces, lowercase)
- Check if the group exists using
in
- Then check if the resource is in that group's list
- Handle all edge cases with user-friendly messages
How to Make it Harder
- Add support for default fallback access if group is unknown
- Allow comma-separated group memberships (multiple group access)
- Use sets instead of lists for faster lookups
Task 2: Suspicious Phrase Detector
You’re writing a script for email filtering. The program should check if any suspicious phrase from a predefined list (e.g.,
["free money", "click here", "urgent"]
) exists in the body of an email (entered by the user). If any of these phrases are found, print "Warning: Suspicious content
detected." Otherwise, print "Email looks clean." Bonus: print which phrase was detected.
What this Task Teaches
This task demonstrates how in
works not only with containers but with substrings in larger strings. It highlights the use of loops, string matching, and creating
defensive filters — skills essential in building security-focused scripts and data validators.
Hints and Tips
Convert both the input email and suspicious phrases to lowercase to ensure matches are case-insensitive. Use a for
loop to scan through each phrase.
- Use
input()
to get the email content - Convert it to lowercase with
.lower()
- Loop through each phrase and check if it’s
in
the email - Break the loop once a match is found
Common Mistakes
-
Using
in
incorrectly with lists: Make sure to compare strings, not lists or unrelated types. - Forgetting to normalize case: Skipping
.lower()
will cause matches to fail unexpectedly. -
Using
==
instead ofin
: Some may use==
for partial matching, which won’t work. - Not handling punctuation: Periods or commas next to keywords might disrupt detection unless handled.
- Checking before cleaning input: Normalize the input before comparison, not after.
Step-by-Step Thinking
You want to scan for known phrases inside user-provided text. Think like a filter bot: does any suspicious phrase appear inside the message?
- Define a list of dangerous phrases
- Ask for the email body from the user
- Convert everything to lowercase
- Loop through each phrase and check if it’s
in
the email - If a match is found, alert the user and stop
- Otherwise, confirm the content looks safe
How to Make it Harder
- Highlight the exact phrase that triggered the alert
- Count the total number of suspicious phrases found
- Scan multi-line input and ignore punctuation