Python Forum
How do integer objects work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do integer objects work?
#1
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.
x = 5005
y = 5005
print(id(x),id(y))
Considering the text above I should get different addresses but to my surprise, I get the same address. Multiple people also tried the code above and got the same address, what is the cause of this? Would appreciate if it was explained in depth, thanks!
Reply
#2
This thread may perhaps explain the address issue.
Reply
#3
It's not an issue. The variables in Python are not the same as in C for example. It is how the memory in Python works.

x and y are two different names pointing to an address where an integer is stored. Since integers are immutable, if y gets a different value, a new address is reserved and the name "y" is pointing to the new address with a new value. Memory allocation is a time expensive operation so this is made for efficiency.

https://www.youtube.com/watch?v=F6u5rhUQ6dU
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do objects work? pyThon_ 12 4,108 Oct-25-2019, 03:59 PM
Last Post: jefsummers
  Python - Make Json objects to work concurrently through Threads? WeInThis 0 2,587 Sep-22-2017, 11:31 AM
Last Post: WeInThis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020