Loading lessons...
Membership Operators
Membership Operators
Membership operators test whether something appears inside a collection: in and not in.
in
fruits = ["apple", "banana"]
print("banana" in fruits) # True
print("grape" in fruits) # False
Works on strings too
txt = "The best things in life are free!"
print("free" in txt) # True
not in
print("grape" not in fruits) # True
print("banana" not in fruits) # False
Works on any collection
- strings, lists, tuples, sets, dictionaries (checks keys), ranges.
print(3 in (1, 2, 3)) # True
print(2 in range(5)) # True
print("a" in {"a": 1}) # True (checks keys)
In an if
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.