How to Check Whether a Value Is in a Collection in Python with in
"Is this file extension one we accept?" "Is this name on the list?" In Python, the answer is one word: in. It works the same way on sets, lists, strings and dictionaries, and gives True or False. This guide asks it six times on Python 3.15.2.
Syntax
<value> in <collection>
<value> not in <collection>
| Part | What it means |
|---|---|
<value> | What to look for |
in | True when the value is in the collection, False when it isn't |
not in | The opposite |
<collection> | Where to look: a set, a list, a tuple, a string or a dictionary |
The language reference says: "x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s."
The Example
The script checks a set of accepted file extensions, a list of names, a string and a dictionary of stock.
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
suffixes = {".jpg", ".png"}
print(".jpg" in suffixes)
print(".gif" in suffixes)
print(".gif" not in suffixes)
print("rose" in ["daisy", "rose"])
print("ros" in "roses")
print("apples" in {"apples": 4, "pears": 7})

Step 2: Run It
uv run python membership.py
True
False
True
True
True
True

Line by line:
.jpgis in the set,.gifisn't, sonot ingivesTruefor it.roseis one of the list's items.rosis part of the stringroses: on strings,inlooks for a piece of the text.applesis one of the dictionary's keys.
The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Looking for a value in a dictionary: 4 in {"apples": 4} | False: in checks the keys only | Check 4 in stock.values(), which gave True |
Expecting in on a string to match whole words only | "ros" in "roses" is True | Split the text into words first, or compare whole strings with == |
| Mixing capital letters | ".JPG" in {".jpg", ".png"} is False | Lowercase the value first with .lower() |
The reference states the dictionary rule: "All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key."
FAQ
Which collection should I check against?
For a fixed group of values, a set: the tutorial names "membership testing" as a basic use of sets. A list works too, and keeps its order.
Can I use in inside an if?
Yes, it's where you'll use it most: if path.suffix.lower() in suffixes: keeps only the files with an accepted extension.
Conclusion
in answered True or False for a set, a list, a string and a dictionary, and not in gave the opposite. On a string it finds a piece of the text, and on a dictionary it looks at the keys.
Additional Resources
- Membership test operations — the language reference.
- Sets — the Python tutorial.
