Check if Set contains specified Element

 

What You'll Learn: In this tutorial, you'll discover how to check if a set contains a specified item using the in membership operator. This helps you know whether a particular element is part of the set.

Using the in Membership Operator

To check if a set contains a specified element, use the in operator. This expression returns True if the set contains the element, and False otherwise.

Syntax:

python
x in set_1

Examples

  1. Checking if the Set Contains an Element

    • We take a set with some values and check if it contains the element "banana".

    Example Code:

    python
    set_1 = {"apple", "banana", "cherry"}
    x = "banana"
    if x in set_1:
        print("The set CONTAINS the element.")
    else:
        print("The set DOES NOT CONTAIN the element.")
    

    Output: The set CONTAINS the element.

    What's Happening Here?

    • x in set_1 checks if 'banana' is in set_1.
  2. Example where the Set Does Not Contain the Element

    • We take a set with some values and check if it contains the element "fig".

    Example Code:

    python
    set_1 = {"apple", "banana", "cherry"}
    x = "fig"
    if x in set_1:
        print("The set CONTAINS the element.")
    else:
        print("The set DOES NOT CONTAIN the element.")
    

    Output: The set DOES NOT CONTAIN the element.

    What's Happening Here?

    • x in set_1 checks if 'fig' is in set_1.

Try It Yourself: Fun Exercises

  1. Check Your Favorite Colors:
    • Create a set of your favorite colors.
    • Use the in operator to check if a specific color is in the set.
  2. Explore Your Book Collection:
    • Write a set of book titles you've read.
    • Use the in operator to see if a particular book is in your collection.

Summary:

In this Python tutorial, we learned how to check if a set contains a specified element using the in membership operator. This method is straightforward and helps you determine the presence of items in a set. Keep experimenting and have fun with sets in Python!