Skip to content
Related Articles

Related Articles

How to check if a set contains an element in Python?

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Nov, 2021
View Discussion
Improve Article
Save Article

In this article, we will discuss how to check if a set contains an element in python.

Method: 1 Using in operator

This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is present in set , otherwise False.

Syntax:

element in set

where

  • set is an input set
  • element is the value to be checked

Example: Check if an element is present in a set

Python3




# import random module
import random
  
# create a set with integer elements
data = {7058, 7059, 7072, 7074, 7076}
  
  
# check 7058
print(7058 in data)
  
# check 7059
print(7059 in data)
  
# check 7071
print(7071 in data)

Output:

True
True
False

Method 2: Using not in operator

This is an membership operator used to check whether the given value is present in set or not. It will return True if the given element is not present in set, otherwise False

Syntax:

element not in set

where,

  • set is an input set
  • element is the value to be checked

Example: Check if an element is present in a set

Python3




# import random module
import random
  
# create a set with integer elements
data = {7058, 7059, 7072, 7074, 7076}
  
  
# check 7058
print(7058 not in data)
  
# check 7059
print(7059 not in data)
  
# check 7071
print(7071 not in data)

Output:

False
False
True

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!