0

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.

6
  • What kind of objects are being collected and checked, and what have you tried so far? Commented Nov 28, 2018 at 16:27
  • Can you modify the Node class (e.g. add a method)? Commented Nov 28, 2018 at 16:29
  • @G.Anderson The objects are instances of a Node class that has multiple attributes, many of them are instances of other classes themselves, some attributes are lists and sets, and few are primitive types. Commented Nov 28, 2018 at 16:29
  • @slider Yes, I have access to it Commented Nov 28, 2018 at 16:29
  • Is __eq__ defined on these classes you're comparing to? Commented Nov 28, 2018 at 16:32

1 Answer 1

1

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') 
Sign up to request clarification or add additional context in comments.

4 Comments

Note that this will have ramifications if you are using Node instances in some of the other built-in containers (e.g. as dict keys)
Will this affect the the way I use node in nodes normally before?
@AhmedHammad can you define "normally". Is that when it was just comparing references? If yes, then in addition to getting True for the same reference, you will also get True if you have another object with the same properties.
Very good! However, hard coding the value comparisons would take hundreds of lines because of the complexity of the Node. If there is a guarantee that there is no way of comparing the values dynamically somehow, I will definitely go with this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.