Python variables have no type, they are just references to objects. The size of a reference is the same regardless of what it is referring to. In the C implementation of Python it is a pointer, and does have a type, it a pointer to a Python object: PyObject *
. The pointer is the same type regardless of class of object. Objects, on the other hand, know which class they belong to.
It has been argued that Python has no variables, only names, although that's a step too far for most people.
References in the CPython implementation have an id (identifier) which is actually a virtual address. The detail and value of this address is not worth pursuing - it can (and probably will) change between versions and is not meant to be used for anything other than a unique number identifying the object. Nevertheless it can provide interesting pointers (pardon the pun) to what is happening:
>>> x = 42
>>> y = x
>>> id(x)
4297539264
>>> id(y)
4297539264
Note that the id (address) of x
and y
are the same - they are referencing the same object, an int
with the value 42. So, what happens when we change x
, does y
change as well?
>>> x = "hello"
>>> id(x)
4324832176
>>> id(y)
4297539264
Thankfully not. Now x
is just referring to a new object of class str
with the value "Hello".
When we:
>>> id(y)
4297539264
>>> y = 37
>>> id(y)
4297539104
The id of y
changed! This is because it is now referencing a different object. int
s are immutable, so the assignment y = 37
did not change the original object (42) it created a new one. The object with the value 42 has its reference count decremented and can now (in theory) be deleted. In practice it would probably remain in memory for efficiency reason, but that's an implementation detail.
However, let's try this for a list:
>>> a = [1,2,3,4]
>>> b = a
>>> id(a)
4324804808
>>> id(b)
4324804808
>>> a[0] = 99
>>> b
[99, 2, 3, 4]
So changing the list a
has changed b
! This is because lists in Python (unlike, say in R) are mutable, so they can change in-place. The assignment b = a
only copied the reference and thus saved memory (no data was actually copied). Dictionaries are another object with such behavior. See copy in the standard library.
type
objects uses'class'
, not'type'
; this was done to reflect that C-defined types are just classes too. – Mavis