1
class Node:
    def __init__(self,left=None,right=None,val=0):
        self.left=left
        self.right=right
        self.val=val

#creating a tree      
abc=Node(val=1)
abc.left=Node(val=2)
abc.right=Node(val=2)
abc.left.left=Node(val=3)
abc.left.right=Node(val=3)
abc.right.left=Node(val=3)
abc.right.right=Node(val=3)

print(abc.left == abc.right)  

Output: False

I Understand they can be stored in different memory locations but "==" operator compares the equality or value of 2 objects. So how are the 2 nodes different?.

This is what ChatGPT told me, is it correct?

the == operator compares the values in the case of lists, but compares the objects themselves in the case of instances of a class like Node.

  • They both are distinct objects. `abc.left,abc.right` and `==` operator check both `values` as well as `object`. – Yash Mehta Apr 04 '23 at 04:15

1 Answers1

0

The reason it output False you are creating both objects as distinct. == operator checks the value as well as the object hence as they are distinct it will return False

To make the abc.left==abc.right -> True you need to assign both as a same object.

Code:

class Node:
    def __init__(self,left=None,right=None,val=0):
        self.left=left
        self.right=right
        self.val=val
    
abc=Node(val=1)
abc.left=Node(val=2)
abc.right=abc.left  # Assigning abc.right as the same object as abc.left
abc.left.left=Node(val=3)
abc.left.right=Node(val=3)
abc.right.left=Node(val=3)
abc.right.right=Node(val=3)

print(abc.left == abc.right) #True
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
  • as per my understanding "==" focuses only on equality, "is" operator focuses on identity, a=[1,2,3] b=[1,2,3] print(hex(id(a)),hex(id(b))) print(a==b) --> true print(a is b) --> false "a" and "b" are different objects but on comparision using "==" give True as output – User_04_04_2023 Apr 04 '23 at 04:39
  • 1
    But `==` defaults to `is` for objects, unless you define your own `__eq__` function. – Frank Yellin Apr 04 '23 at 04:44
  • https://stackoverflow.com/a/70685342/20172954 see the answer and the link provided by this answer.. This will clear your doubt. @User_04_04_2023 – Yash Mehta Apr 04 '23 at 05:01