in operator (membership)
The in operator checks whether a value is inside a list, string, dictionary or set, and gives True or False. not in checks the opposite.
value in collection
value not in collectionx in items asks "is x one of the items?" and gives back True or False. not in gives the opposite answer. It reads almost like English, which makes if conditions very clear.
What counts as "inside" depends on the type. In a list or tuple, in compares with every item. In a string, it looks for a piece of text (a substring). In a dictionary, it checks the keys, not the values.
Speed differs too: checking a list or string walks through it item by item, while sets and dictionaries answer almost instantly even with millions of entries. The same word in is also part of the for loop loop, where it means something else: "take each item from".
Return value
True or False.
Examples
1In a list
guests = ["Ana", "Ben", "Chloe"]
print("Ben" in guests)
print("Dan" in guests)
print("Dan" not in guests)True False True
2In a string: search for text
email = "maria.lopez@example.org"
print("@" in email)
print("lopez" in email)
print("Lopez" in email)True True False
The check is case-sensitive. Use .lower() on both sides to ignore case.
3In a dictionary: checks the keys
stock = {"apples": 4, "pears": 0}
print("pears" in stock)
print(4 in stock)
print(4 in stock.values())True False True
4Inside an if
A tuple of allowed values plus in replaces a long chain of or.
command = "stop"
if command in ("stop", "quit", "exit"):
print("Shutting down")
else:
print("Running:", command)Shutting down
5Fast lookups with a set
banned = {"spam", "scam", "fake"}
words = "this is not a scam offer".split()
flagged = [w for w in words if w in banned]
print(flagged)['scam']
Common mistakes
Expecting in to search dictionary values
value in my_dict only looks at the keys. Use value in my_dict.values() for values.
Writing x == a or b instead of in
if day == "Sat" or "Sun": is always true. Write if day in ("Sat", "Sun"):.
day = "Mon"
print(day == "Sat" or "Sun")
print(day in ("Sat", "Sun"))Sun False
Questions people ask
How do I check if a string contains a word?
"cat" in sentence. For whole words only, split first: "cat" in sentence.split().
How do I check if a key exists in a dictionary?
if key in d:. Or use dict.get() to read it with a default.
Why is in slow on my big list?
A list is searched one item at a time. Convert it to a set once (s = set(items)) and check x in s.