Ahmed Hammad
Ahmed Hammad

Reputation: 3085

Check if an object IN a list with the same VALUE

I have a Python list of some complex objects, and a target object which I wish to check of its occurrence in the list by value.

In other words, I need to find if any of the objects in the list, has the same attributes with the same values as the target object.

I tried:

if node in nodes:

But this compares the references of the objects not the values.

I know I can do some nested loops to check every single attribute, but I am looking for a smarter way, if any.

Upvotes: 0

Views: 927

Answers (1)

slider
slider

Reputation: 12990

You can define the Node class's __eq__ method to compare interesting properties with other nodes:

class Node:
    def __init__(self, val1, val2):
        self.val1 = val1
        self.val2 = val2

    def __eq__(self, other):
        return self.val1 == other.val1 and self.val2 == other.val2


nodes = [Node(1, 2), Node(3, 4), Node(5, 6)]
node = Node(1, 2)
print(node in nodes) # True

If you don't want to write an __eq__ method for fear of breaking old behavior, you can perhaps write a custom equality method that only checks certain properties and then use any. For example:

def val1s_equal(n1, n2):
    return n1.val1 == n2.val1

if any(val1s_equal(node, n) for n in nodes):
    print('do something')

Upvotes: 1

Related Questions