+91 81900 98289

Python __contains__

This Python __contains__ lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

__contains__ answers the in operator. Return True or False.

Without it, Python tries to iterate the object and compare each item.

Example 1: Start here

not in uses the same method and flips the answer.

class Batch: # a template for objects def __init__(self, names): # runs when you create the object self.names = names # store this on the object def __contains__(self, name): # define the function; it runs when you call it return name in self.names # send this value back to the caller print("Meera" in Batch(["Meera", "Arun"])) # in is True when the value is found

Example 2: in on your object

__contains__ answers the in operator.

class Roster: # a template for objects def __init__(self, names): # runs when you create the object self.names = names # store this on the object def __contains__(self, name): # define the function; it runs when you call it return name in self.names # send this value back to the caller print("Asha" in Roster(["Asha", "Arun"])) # in is True when the value is found

Example 3: A case-insensitive test

The method can normalize the text before it compares.

class Roster: # a template for objects def __init__(self, names): # runs when you create the object self.names = names # store this on the object def __contains__(self, name): # define the function; it runs when you call it return name.lower() in [item.lower() for item in self.names] # send this value back to the caller print("asha" in Roster(["Asha"])) # in is True when the value is found

Example 4: Without the method

Lists already support in. Write __contains__ only for your own class.

names = ["Asha", "Arun"] # a list; the values stay in this order print("Asha" in names) # in is True when the value is found
not in uses the same method and flips the answer.
Call Now 81900 98289