Membership Testing
Membership testing uses in to check whether something is present.
Use it with strings, lists and dictionaries to get True or False.
in a string
Use in to check whether text appears anywhere inside a string:
print("e" in "hello")print("z" in "hello")print("ell" in "hello")This prints True, False, then True. You can search for several letters together.
Matching is case-sensitive: "E" in "hello" is False.
in a list
A list checks for a whole item. Use not in to check whether an item is absent:
names = ["Alice", "Bob", "Cara"]print("Bob" in names)print("Bo" in names)print("Dan" not in names)This prints True, False, then True. "Bo" is only part of "Bob",
so it does not match a list item. "Dan" is absent, so not in gives True.
in a dictionary
A dictionary checks its keys, not its values:
scores = {"Alice": 10, "Bob": 7}print("Alice" in scores)print(10 in scores)This prints True, then False: "Alice" is a key, but 10 is a value.
Using it in a condition
Use the membership check directly after if:
story = "The small dog ran home."word = "small"if word in story: print("Found the text")else: print("Text not found")This prints Found the text because word appears in story.
String membership matches text inside longer words too: "small" in "smallest" is True.
See also: Lists, Dictionaries, Comparisons and Logical Operators.
Your turn
Print whether letter occurs in word, then whether the uppercase letter occurs in it.
True False
word = "orange"letter = "a"# Print letter in word, then "A" in word.Advanced reading
- Searching strings — find a match's position, count matches, or check the start and end.