+ 6
Why doesn't this code print 'yes' ? Should I go back to study = and == again:|
8 Respuestas
+ 9
Prashanthi Reddy , as Jayakrishna🇮🇳 already mentioned, the id() function returns a number that can be seen as a memory address of a python object. Normally you don't need this id. But python is a bit strange in some cases of memory management. And so it can be necessary to check or compare the id's of 2 objects.
+ 7
If you use id() you get the object id from a and b and compare them. as a and b are individual objects of list, the result of your code will show "no"
+ 3
Lothar don't know if its a valid question, what does id() or object id refer to?
+ 2
Thanks 😊Divya Mohan now I get it
+ 1
I don't know python, but I'll give it a shot.
The lists a and b hold different addresses. a holds the address to the list [1,2] and b holds the address to [1,2]
If you change a's element 0 to 3, a will be [3,2] and b will stay as [1,2].
What this shows is that a and b are two separate objects and are stored in different addresses in memory.
EDIT: replaced a and b with id(a) and id(b) due to lack of python knowledge and how objects are assigned
id(a) and id(b) don't hold array, they hold the address to that array in memory; when you compare id(a) and id(b) with ==, you aren't comparing the elements in the array, you are comparing the addresses.
So the code sees something like
List@66id7sud6 == List@73ur7rk3i
These values aren't the same so it's false
If you do id(a) == id(a)
it sees
List@66id7sud6 == List@66id7sud6
these values are the same so it's true.
+ 1
I think you should run this
a,b = [1,2],[1,2]
if id(a) == id(b):
print("yes")
else:
print("no")
print(id(a))
print(id(b))
to get clear
+ 1
id(a) returns object 'a' memory address..