The content is different but while applying comparison operator it give "true" how and why?

x=10
x=11
print(id(x))
print(id(x))
print(x is x) #Address Comparison
print(x==x) #Content Comparison

1837655550576
1837655550576
True
True

1 Like

@mannsg001
In the given code snippet, the variable x is first assigned the value of 10, and then later assigned the value of 11. When we print the id(x) twice, we get the same memory address, indicating that the x variable is still referring to the same memory location even after its value has been changed. This is because integers are immutable in Python, which means that their value cannot be changed after they are created.

Therefore, when we compare x with itself using the is operator (address comparison), we get True because both instances of x are referring to the same memory location.

Similarly, when we compare x with itself using the == operator (content comparison), we get True because the content of the memory location pointed to by both instances of x is the same (i.e., 11).

So even though the value of x has been changed, the memory address it refers to has not, and this is why both address comparison and content comparison return True.

2 Likes

@rrnayak2609
Nice explanation :+1::+1:
Keep it up

1 Like

@kaushal-ta-ds
Thank you sir :grinning:

1 Like