Search an item inside a Set in Python
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:
|
1 2 3 4 5 6 |
nums = {6, 4, 5, 9, 8} item = 4 isPresent = item in nums print(isPresent) # True |
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:
|
1 2 3 4 5 6 |
nums = {6, 4, 5, 9, 8} item = 4 isPresent = nums.__contains__(item) print(isPresent) # True |
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:
|
1 2 3 4 5 |
nums = {6, 4, 5, 9, 8} item = 4 isPresent = {item}.issubset(nums) print(isPresent) # True |
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:
|
1 2 3 4 5 6 7 8 |
import numpy nums = {6, 4, 5, 9, 8} item = 4 nums = numpy.array(list(nums)) isPresent = numpy.isin(item, nums) print(isPresent) # True |
That’s all about searching for an item inside a set in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)