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:
x in set_1
Examples
Checking if the Set Contains an Element
- We take a set with some values and check if it contains the element "banana".
Example Code:
pythonset_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_1checks if 'banana' is inset_1.
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:
pythonset_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_1checks if 'fig' is inset_1.
Try It Yourself: Fun Exercises
- Check Your Favorite Colors:
- Create a set of your favorite colors.
- Use the
inoperator to check if a specific color is in the set.
- Explore Your Book Collection:
- Write a set of book titles you've read.
- Use the
inoperator 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!