Python __contains__: A Comprehensive Guide

Introduction

Python’s built-in function `__contains__()` is a powerful tool that allows us to check if a specific value exists in a given sequence. This function can be used with several data types, including strings, lists, tuples, and sets. When we use the `__contains__()` function, Python checks whether the specified value is present in the sequence or not. If the value is present, the function returns True; otherwise, it returns False. Let’s explore how to use and implement the __contains__ method in Python!

What is the “__contains__” method?

In Python, the “__contains__” method is a built-in method that allows us to check whether a specific element exists in a collection or not. It is used with the “in” keyword to test if an object is contained within another object.

The “__contains__” method should be defined within a class, and it takes two parameters: self and item. The “self” parameter refers to the instance of the class that is calling the method, while the “item” parameter refers to the element that we’re checking for.

Here’s an example:


class MyList:
    def __init__(self, data):
        self.data = data

    def __contains__(self, item):
        return item in self.data

my_list = MyList([1, 2, 3, 4, 5])
print(3 in my_list)   # True
print(6 in my_list)   # False

In this example, we define a class called “MyList” which has a constructor that takes a list as its argument. We then define the “__contains__” method which checks whether an item is contained within the list using the “in” keyword. Finally, we create an instance of our custom list and test whether certain elements are contained within it.

The “__contains__” method can be very useful when working with custom classes or data structures. By defining this method, we can make our objects behave like built-in Python objects and take advantage of all the useful features that come with them.

How does the “__contains__” method work?

The “__contains__” method is a built-in method in Python that allows you to check if a specific value or substring is present in a sequence such as string, list, tuple, etc. The method returns a boolean value True if the item is present in the sequence and False otherwise.

To use the “__contains__” method, you simply call it on the sequence object and pass in the item you want to search for as an argument. Here’s an example:


my_list = [1, 2, 3, 4, 5]
print(3 in my_list) # Output: True
print(6 in my_list) # Output: False

In this example, we have a list of numbers and we’re using the “in” keyword to check if the number 3 and 6 are present in the list. The first print statement returns True because 3 is present in the list while the second print statement returns False because 6 is not present in the list.

The “__contains__” method can also be used with strings to check if a particular substring is present. Here’s an example:


my_string = "Hello World"
print("World" in my_string) # Output: True
print("Python" in my_string) # Output: False

In this example, we’re checking if the substring “World” and “Python” are present in the string “Hello World”. The first print statement returns True because “World” is present in the string while the second print statement returns False because “Python” is not present in the string.

Overall, the “__contains__” method provides a simple and convenient way to check if a specific value or substring is present in a sequence.

Examples of using the “__contains__” method in Python

The “__contains__” method in Python is a built-in method that allows us to check if a particular value exists within an object or container. In this section, we will explore some examples of using the “__contains__” method in Python.

Example 1: Using “__contains__” with Strings


# Using __contains__ with Strings
string = "Python is awesome"
if "is" in string:
    print("Yes, 'is' is present in the given string.")
else:
    print("No, 'is' is not present in the given string.")

Output:

Yes, ‘is’ is present in the given string.

In this example, we have used the “__contains__” method to check if the substring “is” exists within the string “Python is awesome”. As we can see from the output, the substring “is” does exist within the string.

Example 2: Using “__contains__” with Lists


# Using __contains__ with Lists
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
    print("Yes, '3' is present in the given list.")
else:
    print("No, '3' is not present in the given list.")

Output:

Yes, ‘3’ is present in the given list.

In this example, we have used the “__contains__” method to check if the value “3” exists within the list [1, 2, 3, 4, 5]. As we can see from the output, the value “3” does exist within the list.

Example 3: Using “__contains__” with Custom Objects


# Using __contains__ with Custom Objects
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

people_list = [Person("John", 25), Person("Jane", 30), Person("Bob", 35)]
if Person("John", 25) in people_list:
    print("Yes, 'John' is present in the given list.")
else:
    print("No, 'John' is not present in the given list.")

Output:

Yes, ‘John’ is present in the given list.

In this example, we have used the “__contains__” method to check if a custom object of class “Person” exists within a list of person objects. As we can see from the output, the object with name “John” and age 25 does exist within the list.

These are just a few examples of how to use the “__contains__” method in Python. This method can be used with any object that supports membership testing, such as sets, tuples, dictionaries, etc.

Customizing the “__contains__” method for your own classes

In Python, the `__contains__` method is used to define custom behavior for the `in` operator. This method is called when an object is searched for within a container using the `in` keyword.

By default, built-in container types like lists and dictionaries have their own implementation of the `__contains__` method. However, you can customize this method for your own classes to define what it means for an object to be “contained” within your class.

To do this, you simply need to define the `__contains__` method within your class definition. The method should take two parameters: `self`, which refers to the instance of the class, and `item`, which refers to the object that is being searched for.

Here’s an example:


class MyClass:
    def __init__(self, items):
        self.items = items
        
    def __contains__(self, item):
        return item in self.items

In this example, we have defined a custom `MyClass` that takes a list of items as input. We then define the `__contains__` method to check if an item is contained within that list.

Now we can use the `in` operator with instances of our class:


my_class = MyClass([1, 2, 3])
print(2 in my_class)  # Output: True
print(4 in my_class)  # Output: False

As you can see, we have customized the behavior of the `in` operator for our own class by defining the `__contains__` method. This allows us to create more intuitive and specialized classes that behave exactly as we want them to.

Conclusion

In conclusion, the __contains__() method is a useful built-in Python method that can be used to determine if an element is present in a sequence or iterable. This method returns a boolean value of True if the element is present in the sequence and False if it is not.

It is important to note that the __contains__() method can be implemented for custom classes as well. This allows developers to define their own logic for determining if an element is present in their custom objects.

Overall, the __contains__() method provides a convenient way to check if an element exists within a sequence or iterable. It is a simple yet powerful tool that can be used to streamline many Python programs.
Interested in learning more? Check out our Introduction to Python course!


How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!


Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Data Science, Tutorials

Guide to NLTK – Natural Language Toolkit for Python

Introduction Natural Language Processing (NLP) lies at the heart of countless applications we use every day, from voice assistants to spam filters and machine translation. It allows machines to understand, interpret, and generate human language, bridging the gap between humans and computers. Within the vast landscape of NLP tools and techniques, the Natural Language Toolkit […]

Machine Learning, Tutorials

GridSearchCV with Scikit-Learn and Python

Introduction In the world of machine learning, finding the optimal set of hyperparameters for a model can significantly impact its performance and accuracy. However, searching through all possible combinations manually can be an incredibly time-consuming and error-prone process. This is where GridSearchCV, a powerful tool provided by Scikit-Learn library in Python, comes to the rescue. […]

Python Basics, Tutorials

Plotting Time Series in Python: A Complete Guide

Introduction Time series data is a type of data that is collected over time at regular intervals. It can be used to analyze trends, patterns, and behaviors over time. In order to effectively analyze time series data, it is important to visualize it in a way that is easy to understand. This is where plotting […]