Python – Check if Set contains specified Element

Python – Check if set contains specified Element

To check if a set contains specified item in Python, you can use in membership operator.

The expression to check if the set set_1 contains the element x is

x in set_1

This expression returns True if the set contains the element x, or False otherwise.

Since this expression returns a boolean value, we can use this expression as a condition in if, if else, or if elif statements.

Examples

1. Checking if the sets contains specified element in Python

In this example, we take a set in set_1 with some initial values, and check if the set contains the element “banana” using in membership operator.

Python Program

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.")
Run Code Copy

Output

The set CONTAINS the element.

Since the set contains the specified element, the condition x in set_1 returned True, and the if-block is executed.

2. Example where the set does not contain the element

In this example, we take a set in set_1 with some initial values, and check if the set contains the element "fig".

Python Program

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.")
Run Code Copy

Output

The set DOES NOT CONTAIN the element.

Since the set does not contain the specified element, the condition x in set_1 returned False, and the else-block is executed.

Summary

In this tutorial of Python Sets, we learned how to check if the set contains a specified element in Python, with examples.

Related Tutorials

Code copied to clipboard successfully 👍