Loading lessons...
Membership Operators
Membership operators test whether something appears inside a collection: in and not in.
in
python
fruits = ["apple", "banana"]
print("banana" in fruits)
### True
print("grape" in fruits)
### False
Works on strings too
python
txt = "The best things in life are free!"
print("free" in txt)
### True
not in
python
print("grape" not in fruits)
### True
print("banana" not in fruits)
### False
Works on any collection
- strings, lists, tuples, sets, dictionaries (checks keys), ranges.
python
print(3 in (1, 2, 3))
### True
print(2 in range(5))
### True
print("a" in {"a": 1})
### True (checks keys)
In an if
python
if "apple" in fruits:
print("We have apples!")
TL;DR
inreturns True if a value is inside a collection.not inreturns the opposite.- Works on strings, lists, tuples, sets, dicts (keys), ranges.