Python – Check if specific element is present in Set

To if a specific element is present in a Set in Python, you can use Python In operator/keyword. Python In membership operator checks if the given element is present in the right operand iterable.

The syntax of the boolean expression to check if element e is present in the set s using in operator is

e in s

The above expression returns True if e is in s, else it returns False.

Examples

ADVERTISEMENT

1. Positive Scenario – Element is present in the Set

In the following program, we initialize a Python Set aSet and check if the element 'cherry' is present in the set.

Program

aSet = {'apple', 'cherry', 'banana'}
element = 'cherry'

# check if element in set
if element in aSet:
    print(f'{element} is present in set')
else:
    print(f'{element} is not present in set')
Try Online

Output

cherry is present in set

2. Negative Scenario – Element is not present in the Set

In the following program, we initialize a Python Set aSet and check if the element 'mango' is present in the set. Since the specified element is not present in the set, the membership operator must return False.

Program

aSet = {'apple', 'cherry', 'banana'}
element = 'mango'

# check if element in set
if element in aSet:
    print(f'{element} is present in set')
else:
    print(f'{element} is not present in set')
Try Online

Output

mango is not present in set

Conclusion

In this Python Tutorial, we learned how to iterate over the elements of a given Set using For loop, with the help of example programs.