0

a=10 b=10 print(id (a) is id (b)) output=false. Why?

29th Oct 2023, 5:04 PM
Devraj Naik
Devraj Naik - avatar
5 Réponses
+ 13
Devraj Naik , In Python, the `id()` function returns the unique identifier for an object. Even though `a` and `b` have the same value of 10, they are separate objects with different memory addresses. That's why, `id(a) is id(b)`return `False`. check this... https://www.geeksforgeeks.org/id-function-python/ https://www.digitalocean.com/community/tutorials/python-id
29th Oct 2023, 7:59 PM
Darpan kesharwani🇮🇳[Inactive📚]
Darpan kesharwani🇮🇳[Inactive📚] - avatar
+ 8
Lothar , a = 10 print(id(a)) ->510871984720 b = 10 print(id(b)) ->510871984720 `print(id(a) is id(b)) # Output: False` In this , both `a` and `b` have the same value of 10, and they share the same memory address. However,it returns False because it compares the memory addresses themselves, not the values stored in those addresses.
31st Oct 2023, 3:34 AM
Darpan kesharwani🇮🇳[Inactive📚]
Darpan kesharwani🇮🇳[Inactive📚] - avatar
+ 6
print( a == b) #true print( type(a) == type(b)) #true print( id(a) == id(b) ) #true print( id(a) is id(b) ) #false
30th Oct 2023, 3:36 AM
Jayakrishna 🇮🇳
+ 5
Darpan kesharwani🇮🇳 , sorry to say, but your explanation of the problem is not correct. it would be better to run a test to verify your statement. a = 10 print(id(a)) # result -> 510871984720 b = 10 print(id(b)) # result -> 510871984720 >>> both variables are showing the same id value. there is only one object, but 2 variables that are pointing to it. this behaviour of python means, that variable *a* and *b* share the same value of 10. so we can expect that the following expression results in True: print(id(a) is id(b)) # result -> False but the result shows False. you may get a better understanding of this by reading this article from *stackoverflow*: https://stackoverflow.com/questions/50893267/how-can-two-python-objects-have-same-id-but-is-operator-returns-false
30th Oct 2023, 7:32 PM
Lothar
Lothar - avatar
+ 4
As a rule, you should use the is operator to compare objects and not IDs. Because you will get undesirable results. Because of memory efficiency and object reuse in Python, two different variables that hold the same value might share the same memory address. A and b are different references sharing the same memory address, therefore print(id(a) is not id(b))) # true The most reliable way to check if two variables point to the same object is by using the is operator directly on the variables themselves: print(a is b) The id sharing the same memory address made this confusing. But this helped me understand why it was happening. https://embeddedinventor.com/python-is-and-is-not-explained-with-examples/
31st Oct 2023, 7:22 AM
Chris Coder
Chris Coder - avatar