This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: More on lists

List membership operator

face Josiah Wang

The membership operator (in) can be used to check whether a particular object is in a list. This returns a bool (so True or False).

>>> print(3 in [1, 2, 3, 4])
True
>>> print(3 not in [1, 2, 3, 4])
False
>>> print("snake" in ["I", "am", "not", "afraid", "of", "Python"])
False

Try it out!

1 2 3

Question 1

What is the output of the following code snippet? Type Error if it results in an error.

numbers = [1, 2, 3, 4]
print(2+2 in numbers)

True

Question 2

What is the output of the following code snippet? Type Error if it results in an error.

vowels = ["a", "e", "i", "o", "u"]
character = "c"
print(character not in vowels)

True

Question 3

What is the output of the following code snippet? Type Error if it results in an error.

allowed_symbols = ["@", "-", "*", "_"]
symbol = "@"
if symbol not in allowed_symbols:
    print("Not allowed")
else:
    print("Allowed")

Allowed
Explanation:

The in and not in boolean expressions can be used as if and while conditions. Python recommends using x not in y rather than not x in y for better readability.