Python Membership Operators
Table of Contents + โ
In the last lesson you learned Assignment Operators. Those are about putting a value into a variable. Now we ask a different question. We already have a value. We want to know one thing. Is it sitting inside this group of things or not? That is exactly what membership operators answer.
๐ค Why Membership Operators?
Say you have a list of usernames who are allowed into an app. Someone types their name. You need to know one thing fast. Is this name in the allowed list or not?
You could write a loop that walks through every name and compares them one by one. That works. But it is a lot of code for a simple yes-or-no question. Python gives you a shorter way. The membership operators let you ask โis this value inside that group?โ in plain words. You get back True or False.
๐งฉ What Are in and not in?
Python has two membership operators.
inasks: is this value somewhere inside the sequence? You getTrueif it is, andFalseif it is not.not inis the opposite. It givesTruewhen the value is missing.
A sequence here just means a group of values in order. A string of characters is one. A list of items is another. Think of in like checking a guest list. You stand at the door. You look down the list. You ask one question. Is this name on it? You do not care where on the list it is. You only care yes or no.
Here is the basic shape. We check single characters and whole items.
print("a" in "cat") # is the letter "a" inside the word "cat"?print("z" in "cat") # is the letter "z" inside the word "cat"?print("dog" not in "cat") # is "dog" missing from "cat"?Output
TrueFalseTrueLetโs read those lines. "a" in "cat" is True. The word โcatโ really does contain the letter a. "z" in "cat" is False. There is no z anywhere in โcatโ. And "dog" not in "cat" is True. The word โcatโ does not contain โdogโ, so the โis it missing?โ question comes back yes.
The reason this is so useful is simple. Every result is a boolean. It is just True or False. So you can use these operators anywhere you need a yes-or-no answer, like inside an if statement.
๐ Checking If an Item Is in a List
Strings are nice for a first look. But the everyday use is with lists. A list is just a group of items in square brackets. We want to know if a certain item is one of them.
This snippet checks whether a fruit is in our basket.
fruits = ["apple", "banana", "mango"]
print("banana" in fruits) # is "banana" one of the items?print("orange" in fruits) # is "orange" one of the items?print("orange" not in fruits)Output
TrueFalseTrueSee how it reads almost like English? "banana" in fruits checks the whole word โbananaโ against each item in the list. It found a match, so the answer is True. There is no โorangeโ in the list, so the second line is False. And asking if it is not in the list comes back True.
Caution
With a list, in matches a whole item, not a piece of it. So "app" in ["apple"] is False. The value โappโ is not the same item as โappleโ. But with a string, "app" in "apple" is True. There it is searching for the letters inside the word. Same operator, but the kind of value changes what counts as a match.
๐ A Real Use: An Allowed-Users Check
Now the real example from the start. We have a short list of usernames allowed into an app. A person types a name. We decide whether to let them in.
We take the typed name and ask if it belongs to the allowed group.
allowed_users = ["alex", "riya", "arjun"]username = "riya"
if username in allowed_users: print(f"Welcome back, {username}!")else: print("Sorry, you are not on the list.")Output
Welcome back, riya!Letโs walk through it line by line.
allowed_usersholds the names we trust.usernameis the name the person gave us. Here it is"riya".if username in allowed_users:is the check. It asks if the value ofusernameis one of the items in the list. It is, so the answer isTrue.- Because the answer is
True, Python runs the firstprint. If the name had been missing, it would run theelseline instead.
That one line, username in allowed_users, replaced a whole loop. That is the point of these operators.
๐ Searching for Text Inside a String
One more handy use. With strings, in does not only check single letters. It can search for a whole smaller piece of text inside a bigger one. That smaller piece is called a substring. A substring just means a run of characters that sits inside another string.
This checks whether a word appears inside a sentence.
message = "Your order has shipped"
print("shipped" in message) # does the sentence contain this word?print("delayed" in message)Output
TrueFalseSo "shipped" in message is True. Those exact letters, in that order, really are inside the sentence. This is great for a quick check like โdoes this email contain the word refund?โ without any heavy text tools.
Tip
Membership checks on strings are case-sensitive. The words "shipped" and "Shipped" are not the same to Python. If you want to ignore case, lower both sides first, like "shipped" in message.lower().
๐ Quick Reference
Here is the whole idea in one place.
| Expression | Asks | Result |
|---|---|---|
"a" in "cat" | Is the letter in the word? | True |
"z" in "cat" | Is the letter in the word? | False |
"banana" in fruits | Is the item in the list? | True |
"orange" not in fruits | Is the item missing? | True |
โ ๏ธ Common Mistakes
A few things trip people up early on.
- Mixing up the order. The value you are looking for goes on the left. The group goes on the right. It reads left to right like a sentence.
fruits = ["apple", "banana"]
# โ Avoid: this asks if the list is inside the word, which is not what you wantprint(fruits in "banana")
# โ
Good: value first, then the group you are searchingprint("banana" in fruits)- Forgetting that list matching needs the whole item. A piece of a word will not match a list item.
names = ["alexander"]
# โ Avoid: "alex" is not the same item as "alexander"print("alex" in names) # False
# โ
Good: search the text inside the string insteadprint("alex" in "alexander") # True- Forgetting case matters. The values
"Riya"and"riya"are different, so a check can come backFalsewhen you expectedTrue.
โ Best Practices
Small habits that keep these checks clean.
- Use
ininstead of writing a loop when all you need is a yes-or-no answer. It is shorter and easier to read. - Read the check out loud before you trust it. The line โis username in allowed_usersโ should sound like the question you actually mean to ask.
- When user input is involved, make the case consistent. Lower both the input and the stored values so a capital letter does not cause a wrong answer.
- Prefer
not inover writingnot (x in y). Both work, butnot inreads the way you think.
๐งฉ What Youโve Learned
A quick recap of what you can now do.
- โ
Use
into check whether a value is inside a string, list, or other sequence, and get backTrueorFalse. - โ
Use
not infor the opposite check, when you want to know if a value is missing. - โ Know that list checks match a whole item, while string checks can find a smaller piece of text inside.
- โ Replace a yes-or-no loop with a single clean membership check, like an allowed-users gate.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does `"a" in "cat"` return?
Why: The letter "a" really is inside the word "cat", so the result is the boolean True.
- 2
Given `fruits = ["apple", "banana"]`, what is `"app" in fruits`?
Why: With a list, in matches a whole item, and "app" is not the same item as "apple", so it is False.
- 3
Which operator checks whether a value is missing from a sequence?
Why: not in returns True when the value is not found inside the sequence.
- 4
What does `"shipped" in "Your order has shipped"` return?
Why: On a string, in searches for the substring, and those exact letters appear in the sentence, so it is True.
๐ Whatโs Next?
You can now ask whether a value lives inside a group. Next we look at a different question. Are these two things actually the very same object in memory? That is what identity operators are for.