Python List Functions: in, sort, min, max, sum
Check If an Item Is in a List with in
The in operator asks: "is this value somewhere in the list?" The answer is True or False. not in asks the opposite question.
Think of the guest list at a party door. The guard checks whether your name is on it before letting you in.
guests = ["Sunny", "Rocky", "Lucky"]
print("Rocky" in guests)
print("sunny" in guests)
print("sunny" not in guests)True False True
The rules
value in listisTruewhen at least one item equals the value.value not in listisTruewhen no item does.- The match must be exact:
"sunny"is not"Sunny", and the text"5"is not the number5.
in with if
in gives True or False, so it makes a perfect if condition (chapter 8). Here a café checks an order typed by the user:
menu = ["tea", "coffee", "juice"]
order = input()
if order in menu:
print(f"One {order} coming up!")
else:
print(f"Sorry, no {order} today.")One coffee coming up!
Try typing lassi in the Input box.
Good: check before you remove
In topic 4, remove() stopped with a ValueError when the value was missing. With in, you check first:
cart = ["milk", "eggs"]
if "bread" in cart:
cart.remove("bread")
else:
print("No bread in the cart")No bread in the cart
Avoid: calling remove() on a value that might not be there. One missing item would stop the whole program.
value in listis True when the list has that item. Check withinbefore youremove().