← Python lessons

Membership Testing

in asks a yes/no question: is this value inside that collection? It works on strings, lists and dictionaries, and it always gives back True or False.

in a string

vowels = "aeiou"
print("e" in vowels)
print("z" in vowels)

For a string, in checks whether the text appears anywhere inside it.

in a list

names = ["Alice", "Bob", "Cara"]
print("Bob" in names)
print("Dan" not in names)

not in is the opposite question, and reads better than writing not (x in y).

in a dictionary

scores = {"Alice": 10, "Bob": 7}
print("Alice" in scores)
print(10 in scores)

A dictionary checks its keys, not its values — which is exactly what you want before looking a key up.

Using it in a condition

answer = "y"
if answer in "yn":
    print("recognised answer")
else:
    print("choose y or n")

This example checks a one-character answer. For strings, in checks for matching text, and the match is case-sensitive: "y" in "yn" is True, while "Y" in "yn" is False.

See also: Lists, Dictionaries, Comparisons and Logical Operators.

Your turn

Print whether letter occurs in word, then whether the uppercase letter occurs in it.

word = "orange"
letter = "a"
# Print letter in word, then "A" in word.

Expected output

True
False

Practise this in the free Python course, where every exercise checks your code instantly.