AppDividend
Latest Code Tutorials

Python set contains: How to Check If Set Contains an Element

0

Python set is a collection of unique, unindexed, and unordered elements. Sets are used to store multiple elements in a single variable.

Python set contains

To check if the set contains an element in Python, use the in keyword, which returns True if the specified set contains an element and False otherwise. The in keyword is used to check if the element is present in a sequence like a list, range, string, set, etc.

The in keyword is also used to iterate through a sequence in a for loop.

When used in a condition, the statement returns a Boolean result evaluating either True or False.

When the specified value is found inside the sequence, the statement returns True. Whereas when it is not found, we get a False.

first_set = {11, 19, 21}

el_in_set = 19 in first_set

print(el_in_set)

Output

True

It returns True because the 19 is included in the set.

Let’s check for element 46 in the existing set and see the output.

first_set = {11, 19, 21}

el_in_set = 46 in first_set

print(el_in_set)

Output

False

We got False because the set does not contain the “46” element.

Python “not in” operator

The not in operator in Python works exactly the opposite way as the in operator works. The not in operator checks the presence of a specified value inside a given sequence but its return values are totally opposite to that of the in operator.

first_set = {11, 19, 21}

el_in_set = 46 not in first_set

print(el_in_set)

Output

True

It returns True because the set does not contain 46. That is why not in operator returns True because it is not in the set. Let’s take an example where the element exists in the set and see the output.

first_set = {11, 19, 21}

el_in_set = 11 not in first_set

print(el_in_set)

Output

False

And it returns False which is correct because 11 exists in the set.

Conclusion

To check if the specified element is present in Set, use the in operator.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.