Why doesn't this code print 'yes' ? Should I go back to study = and == again:| | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Why doesn't this code print 'yes' ? Should I go back to study = and == again:|

https://code.sololearn.com/cLV52h53b4U9/?ref=app

22nd Sep 2020, 2:47 PM
Twilight🌅
Twilight🌅 - avatar
8 Answers
+ 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.
22nd Sep 2020, 7:13 PM
Lothar
Lothar - avatar
+ 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"
22nd Sep 2020, 3:12 PM
Lothar
Lothar - avatar
+ 3
Lothar don't know if its a valid question, what does id() or object id refer to?
22nd Sep 2020, 4:07 PM
Twilight🌅
Twilight🌅 - avatar
+ 2
Thanks 😊Divya Mohan now I get it
23rd Sep 2020, 4:02 AM
Twilight🌅
Twilight🌅 - avatar
+ 2
Thanks 😃 Lothar and Odyel
23rd Sep 2020, 4:05 AM
Twilight🌅
Twilight🌅 - avatar
+ 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.
22nd Sep 2020, 3:01 PM
Odyel
Odyel - avatar
+ 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
22nd Sep 2020, 5:55 PM
Divya Mohan
Divya Mohan - avatar
+ 1
id(a) returns object 'a' memory address..
22nd Sep 2020, 6:45 PM
Jayakrishna 🇮🇳