Searching a List: in

Is a name on the guest list? Is there milk on the shopping list? The operator in answers questions like these. value in items is True if the list items contains the value, and False if it doesn't:

guests = ["Anna", "Tom", "Lucy"]
print("Tom" in guests)
print("Paul" in guests)

This prints:

True
False

A boolean is exactly what a condition needs, so in is most often used with if:

guests = ["Anna", "Tom", "Lucy"]
visitor = "Tom"
if visitor in guests:
    print("Come in!")
else:
    print("Sorry, you are not on the list.")

This prints:

Come in!

The opposite is not in: value not in items is True when the value isn't in the list. It's handy for adding something only if it isn't in the list yet:

shopping = ["milk", "bread"]
item = "eggs"
if item not in shopping:
    shopping.append(item)
print(shopping)

This prints:

['milk', 'bread', 'eggs']

With in, you can also avoid the ValueError from the previous exercise. If you write if "butter" in shopping: before shopping.remove("butter"), the value is removed only when it is in the list.

Like ==, in compares exactly: "tom" in guests is False, because "tom" with a lowercase t isn't the same text as "Tom".

Instructions

Write an if statement with the condition visitor in guests, and in its block, print Come in! (Lucy is on the list, so the program prints it).

Add an else branch that prints Sorry, you are not on the list. Then change the value of visitor to "Paul" (in the line visitor = "Lucy"). Paul isn't on the list, so now the program should print Sorry, you are not on the list.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/12