Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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).

  2. 2

    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.

Back

9/12

  1. 1. Introduction to Lists
  2. 2. Creating Lists
  3. 3. Accessing List Elements
  4. 4. Changing List Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: append()
  7. 7. Removing Elements: pop()
  8. 8. Removing by Value: remove()
  9. 9. Searching a List: in
  10. 10. Nested Lists
  11. 11. Characters of a Text
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.