Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I check if an instance of a class exists in a List in Python 3?

In Python 3, I have a list (my_array) that contains an instance of the Demo class with a certain attribute set on that instance. In my case, the attribute is value: int = 4.

Given an instance of the Demo class, how can I determine if that instance already exists in my_array with the same properties. Here’s a MCRE of my issue:

from typing import List
class Demo:
    def __init__(self, value: int):
        self.value = value
        
my_array: List[Demo] = [Demo(4)]

print(Demo(4) in my_array)  # prints False

However, Demo(4) clearly already exists in the list, despite that it prints False.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I looked through the Similar Questions, but they were unrelated.

How can I check if that already exists in the list?

>Solution :

You need to add an equality function to Demo:

    def __eq__(self, other):
        return isinstance(other, Demo) and self.value == other.value

P.S, since Python 3.9 you don’t need to import List and just use:

my_array: list[Demo] = [Demo(4)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading