Membership (in, not in)
`in` asks whether a value is inside something and answers True or False; `not in` asks the opposite.
Used in 77 lessons of the course, from 00.01.
x in y is an expression that gives True or False. It reads almost like English: "is x in y?". not in flips the answer.
What "inside" means depends on the container:
- In a list, tuple or set, it compares with each element.
- In a dict, it looks at the keys, not the values.
- In a string, it looks for a piece of text (a substring).
That is why if key in GLOSSARY: from lesson 00.01 is a safe way to ask whether the key exists before you use it. It avoids a KeyError when you read GLOSSARY[key].
In a set or dict the lookup is fast. In a list Python checks element by element, but for small lists that doesn't matter.
print("a" in "gato")
Reach for it when: you need to check whether a value is in a collection, whether a key exists in a dict, or whether a text contains another.
Examples
Common mistake
prices = {"apple": 3}
print(3 in prices)Why: On a dict, `in` checks keys, not values. 3 is a value, so it gives False.
How to write it: Use 3 in prices.values() if you want to search the values.
Common mistake
print("cat" in ["concatenate", "dog"])Why: On a list, `in` compares whole elements, not pieces of text. "cat" is not equal to "concatenate".
How to write it: To look for a substring, test each string: any("cat" in w for w in words).
