Skip to content

Python not in set

  • by

In Python, you can use the not in operator to check if an element is not present in a set. The not in operator returns True if the element is not found in the set, and False otherwise.

The not in operator is used to check if an element is not present in a set. Here’s the correct syntax:

element not in set

You can use this syntax to check if an element is not present in a set. The not in operator returns True if the element is not found in the set, and False otherwise.

my_set = {1, 2, 3, 4, 5}

# Check if an element is present in the set
print(3 in my_set)  # Output: True

# Check if an element is not present in the set
print(6 not in my_set)  # Output: True

Python not in set example

Here’s an example that demonstrates the usage of the not in operator with sets in Python:

fruits = {"apple", "banana", "orange", "grape"}

# Check if an element is not present in the set
if "mango" not in fruits:
    print("Mango is not in the set")

# Check if an element is not present in the set
if "banana" not in fruits:
    print("Banana is not in the set")
else:
    print("Banana is in the set")

Output:

Python not in set

Python finds numbers not in set

To find numbers that are not present in a set, you can utilize a range of numbers and the not in operator. Here’s an example that demonstrates this approach:

my_set = {2, 4, 6, 8, 10}

# Define the range of numbers to search for
start_num = 1
end_num = 10

# Find numbers not present in the set
missing_nums = [num for num in range(start_num, end_num+1) if num not in my_set]

print("Numbers not present in the set:", missing_nums)

In this example, the set my_set contains some numbers. We define a range of numbers to search for using the start_num and end_num variables. Then, we use a list comprehension to iterate over the numbers within the range and check if each number is not present in the set my_set using the not in operator. The numbers that are not present in the set are collected in the missing_nums list.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *