This post will discuss how to search for an item inside a set in Python.

1. Using in operator

The standard way to search an item in a set is using the in operator. The in is a built-in operator in Python that allows us to check if an item is contained in an iterable. It evaluates to True if it finds the item in the specified sequence and False otherwise. For example, we can search for number 4 inside a set using the in operator like this:

Download  Run Code

 
The above code prints True as the item 4 is found in the set. It should be noted that the in operator calls the efficient __contains__() function behind the scene. Although not very Pythonic, it can be called directly:

Download  Run Code

2. Using issubset() function

Alternatively, we can use the issubset() function to search for an item inside a set by creating a singleton set with the item and passing it as the argument to the method. This method returns True if a given set is a subset of another set and False otherwise. For example:

Download  Run Code

3. Using numpy.isin() function

We can also use the numpy module to search for an item inside a set. The idea is to convert the set to a numpy array and then call the numpy.isin() function. This function returns a boolean array indicating whether each element of an array is contained in another array. For example:

Download  Run Code

That’s all about searching for an item inside a set in Python.