Understanding Membership Operators in Python

Membership Operators:

Membership operators in Python are used to test whether a value is a member of a sequence or collection. They return boolean values (True or False) based on the presence of the value in the sequence. Here are the two membership operators in Python:

Examples:

Let's see some examples of using membership operators in Python:

        
            # Using 'in' operator with lists
            numbers = [1, 2, 3, 4, 5]
            result = 3 in numbers
            print(result)

            # Using 'not in' operator with strings
            message = "Hello, World!"
            result = "Python" not in message
            print(result)

            # Using 'in' operator with dictionaries
            student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}
            result = "Bob" in student_grades
            print(result)

            # Using 'not in' operator with sets
            fruits = {"apple", "banana", "cherry"}
            result = "orange" not in fruits
            print(result)
        
    

Membership operators are useful for checking the presence of specific elements in collections, allowing you to make decisions based on membership in your Python programs.

Comparison, Logical, and Membership Operators in Python YouTube Video