Skip to content

8.5 Membership operators

8.5a What are Python membership operators

Membership operators in Python are used to test whether a value or variable is found in a sequence (such as a string, list, tuple, set, or dictionary). They are essential for tasks like searching, validating input, and controlling program flow based on the existence of values in data structures. These operators help make your code more efficient and readable when dealing with collections of data. The primary membership operators are:

  • in - Returns True if the specified value is present in the sequence.

Example 8.5.1

'a' in 'apple' 

Example 8.5.1 - Output

True

 

  • not in - Returns True if the specified value is not present in the sequence.

Example 8.5.2

'b' not in 'apple' 

Example 8.5.2 - Output

True

 


 

8.5b Why do we use membership operators?

Membership operators are used to check for the presence or absence of values in sequences. They are very useful for tasks like validating input, searching within data structures, and controlling the flow of programs based on whether certain values are present.

 


 

8.5c Interpret a program snippet that includes membership operators

Example 8.5.3 - Here’s a simple example to demonstrate how membership operators can be used in Python.

# Examples of membership operators

fruits = ["apple", "banana", "cherry"]

# Using 'in' to check if a value is in a list
if "banana" in fruits:
    print("Banana is in the list of fruits.")  # This will be printed

# Using 'not in' to check if a value is not in a list
if "grape" not in fruits:
    print("Grape is not in the list of fruits.")  # This will be printed

Example 8.5.3 - Explanation

  • "banana" in fruits:

    • Condition: Checks if the string "banana" is present in the list fruits.
    • Result: Since "banana" is in the list, the condition is True and it prints "Banana is in the list of fruits."
  • "grape" not in fruits:

    • Condition: Checks if the string "grape" is not present in the list fruits.
    • Result: Since "grape" is not in the list, the condition is True and it prints "Grape is not in the list of fruits."

 


 

Exercise 8.5.1 - Write a Python program that checks if a user's favorite colour is available in a list of available colours. Use the in and not in membership operators to implement the following rules:

  • The program should have a predefined list of available colours: ["red", "blue", "green", "yellow"].
  • Ask the user to input their favorite colour.
  • Convert the user's input to lowercase to handle case insensitivity.
  • Check if the user's favorite colour is in the list of available colours.
  • If the colour is in the list, print a message saying that the colour is available.
  • If the colour is not in the list, print a message saying that the colour is not available.

Exercise 8.5.1 - Model Answer - Make sure to work out the exercise before checking the model answer.