Skip to main content

Section 9.5 List Membership

in and not in are boolean operators that test membership in a sequence. We used them previously with strings and they also work here.
If you want to know where something is in a list, you can use the .index() function. It will return the index where the item is in the list—but if the item is not in the list, it will generate a ValueError.
However, we can use the in operator to make a function that gives us a “safe” index:
Because our safe_index function isn’t built in to the list class, we cannot use it with dot notation.

Checkpoint 9.5.1.

    What is printed by the following statements?
    a_list = [3, 67, "cat", 910.0, 3.14, False]
    print(3.14 in a_list)
    
  • True
  • Yes, 3.14 is an item in the list a_list.
  • False
  • There are six items in the list; 3.14 is one of them.