w3resource

Python: Check if a given value is present in a set or not


16. Check if a Given Value is Present in a Set

Write a Python program to check if a given value is present in a set or not.

Visual Presentation:

Python Sets: Check if a given value is present in a set or not.
Python Sets: Check if a given value is present in a set or not.

Sample Solution:

Python Code:

# Create a set 'nums' with elements 1, 3, 5, 7, 9, and 11.
nums = {1, 3, 5, 7, 9, 11}

# Print a message to indicate the original set 'nums'.
print("Original set (nums): ", nums, "\n")

# Test if the number 6 exists in 'nums' and print the result.
print("Test if 6 exists in nums:")
print(6 in nums)

# Test if the number 7 exists in 'nums' and print the result.
print("Test if 7 exists in nums:")
print(7 in nums)

# Test if the number 11 exists in 'nums' and print the result.
print("Test if 11 exists in nums:")
print(11 in nums)

# Test if the number 0 exists in 'nums' and print the result.
print("Test if 0 exists in nums:")
print(0 in nums)

# Test if the number 6 is not in 'nums' and print the result.
print("\nTest if 6 is not in nums")
print(6 not in nums)

# Test if the number 7 is not in 'nums' and print the result.
print("Test if 7 is not in nums")
print(7 not in nums)

# Test if the number 11 is not in 'nums' and print the result.
print("Test if 11 is not in nums")
print(11 not in nums)

# Test if the number 0 is not in 'nums' and print the result.
print("Test if 0 is not in nums")
print(0 not in nums)

Sample Output:

Original sets(nums):  {1, 3, 5, 7, 9, 11} 

Test if 6 exists in nums:
False
Test if 7 exists in nums:
True
Test if 11 exists in nums:
True
Test if 0 exists in nums:
False

Test if 6 is not in nums
True
Test if 7 is not in nums
False
Test if 11 is not in nums
False
Test if 0 is not in nums
True

For more Practice: Solve these Related Problems:

  • Write a Python program to check whether a user-specified value exists in a set using the in operator.
  • Write a Python program to implement a function that returns True if a value is in a set and False otherwise.
  • Write a Python program to use exception handling to search for an element in a set and return a custom message if not found.
  • Write a Python program to iterate over a set and determine the presence of a specific value using a for-loop.

Go to:


Previous: Write a Python program to find the length of a set.
Next: Write a Python program to check if two given sets have no elements in common.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.