+ 6

How is python working with memory ?

The id function return something like the adress of a variable. But when i do this : id(5) id(5) i get the SAME adress. I thought that in the first line i create a int object with value of 5 then i print its adress and then python should remove it. But then in the second line i thought i was going to create another int object with the same value and so i expected that the adress will be different. So help me please ! https://code.sololearn.com/cG3Gbrt0Cwel/?ref=app

15th Apr 2017, 8:19 AM
Glozi30
Glozi30 - avatar
6 Answers
+ 5
obviously it's useful to do "5 is 5" because "is" compare the 2 objects with their adresses. but to me here come a problem : python has to store an adress for each variable. At first i though it was some hashing but when i try again the code, the adresses are not the same that previously. this works also for strings and lists; id("adress") wil always be the same include if i havn't store a variable "adress".
15th Apr 2017, 8:22 AM
Glozi30
Glozi30 - avatar
+ 5
Thank you for your answer but i've just tried on my computer in the console of python 3.5.1 and I have the same result include with string, lists and integers larger than 255... Maybie python needs optimisations too
15th Apr 2017, 4:41 PM
Glozi30
Glozi30 - avatar
+ 3
I've just done an experience on my computet with python : a while loop that prints all the adress of a variable a that goes from 1 to 300. the 256 first ones are all different then there is an alternation : for example id(257) = id(259) = id(261) ... and id(258) = id(260) = id(262)... i think it works because all the values are destroyed but why is there an alternation. Python is strange... in the console if i write id(300) then id(301) then id(302) here i will get the same adress, so here there no alternation and python create and delete the values normally. Then i can do this : id(300) #output adress 1 id(62557262) #output adress 2 id(300) #ouput adress 2 i really don't understand how does python work with memory...
30th Apr 2017, 1:26 PM
Glozi30
Glozi30 - avatar
+ 2
During initialisation, CPython creates the integers 0-255. There also should be some optimisation in the Playground, especially not recreating the same values... for instance, if you try running your code in any Python console, you should not have the same IDs for the variables that are not integers between 0 and 255
15th Apr 2017, 4:18 PM
Amaras A
Amaras A - avatar
+ 1
well, that's a bit weird... I don't know exactly how Python works, but I know the basics
15th Apr 2017, 4:47 PM
Amaras A
Amaras A - avatar
0
Glozi30 I really feel sorry for you, as no one is answering your question! Maybe because it's beyond the viewers' understanding, I guess.
27th Aug 2021, 5:23 AM
Calvin Thomas
Calvin Thomas - avatar