If I use the below:
a = 1000
print(id(a))
myList = [a,2000,3000,4000]
print(id(myList[0]))
# prints the same IDs
I get the same id. This makes sense to me. I can understand how the memory manager could assign the same object to these variables, because I am directly referencing a
in the list.
However, if I do this instead:
a = 1000
print(id(a))
myList = [1000,2000,3000,4000]
print(id(myList[0]))
# prints the same IDs
I STILL get the same id being output for both prints. How does Python know to use the same object for these assignments? Searching for pre-existence would surely be hugely inefficient so I am presuming something more clever is going on here.
My first thought was something to do with the integer itself being used to calculate the objects address, but the behaviour also holds true for strings:
a = "car"
print(id(a))
myList = ["car",2000,3000,4000]
print(id(myList[0]))
# prints the same IDs
The behaviour does NOT however, hold true for list elements:
a = [1,2,3]
print(id(a))
myList = [[1,2,3],2000,3000,4000]
print(id(myList[0]))
# prints different IDs
Can someone explain the behaviour I am seeing?
EDIT - I have encountered that for small values between -5 and 256, the same object may be used. The thing is that I am seeing the same object still being used even for huge values, or even strings:
a = 1000000000000
myList = [1000000000000,1000,2000]
print(a is myList[0])
# outputs True!
My question is How can Python work out that it is the same object in these cases without searching for pre-existence? Let's say CPython specifically
EDIT - I am using Python V3.8.10