Can someone explain this to me? So I\'ve been playing with the id() command in python and came across this:
>>> id(\'cat\')
5181152
>>> a = \'c
Python variables are rather unlike variables in other languages (say, C).
In many other languages, a variable is a name for a location in memory. In these languages, Different kinds of variables can refer to different kinds of locations, and the same location could be given multiple names. For the most part, a given memory location can have the data change from time to time. There are also ways to refer to memory locations indirectly (int *p
would contain the address, and in the memory location at that address, there's an integer.) But a the actual location a variable references cannot change; The variable is the location. A variable assignment in these languages is effectively "Look up the location for this variable, and copy this data into that location"
Python doesn't work that way. In python, actual objects go in some memory location, and variables are like tags for locations. Python manages the stored values in a separate way from how it manages the variables. Essentially, an assignment in python means "Look up the information for this variable, forget the location it already refers to, and replace that with this new location". No data is copied.
A common feature of langauges that work like python (as opposed to the first kind we were talking about earlier) is that some kinds of objects are managed in a special way; identical values are cached so that they don't take up extra memory, and so that they can be compared very easily (if they have the same address, they are equal). This process is called interning; All python string literals are interned (in addition to a few other types), although dynamically created strings may not be.
In your exact code, The semantic dialog would be:
# before anything, since 'cat' is a literal constant, add it to the intern cache
>>> id('cat') # grab the constant 'cat' from the intern cache and look up
# it's address
5181152
>>> a = 'cat' # grab the constant 'cat' from the intern cache and
# make the variable "a" point to it's location
>>> b = 'cat' # do the same thing with the variable "b"
>>> id(a) # look up the object "a" currently points to,
# then look up that object's address
5181152
>>> id(b) # look up the object "b" currently points to,
# then look up that object's address
5181152