This question is more a curiosity than anything else.
I've been reading the details of the implementation of the int object in Python (1 and 2) and, as far as I can see, a Python int is basically a C pointer to an struct, right?
So the question is basically, what happens in Python internally so equaling two int
s in python doesn't point to the same instance while equaling complex types, such as list
, does:
>>> a=5
>>> b=a
>>> print "id a: %s, id b: %s" % (id(a), id(b))
id a: 40802136, id b: 40802136
>>> b+=1
>>> print "a: %s, b: %s" % (a, b)
a: 5, b: 6
>>> print "id a: %s, id b: %s" % (id(a), id(b))
id a: 40802136, id b: 40802112
>>> a=[5]
>>> b=a
>>> print "id a: %s, id b: %s" % (id(a), id(b))
id a: 45930832, id b: 45930832
>>> b.append(1)
>>> print "a: %s, b: %s" % (a, b)
a: [5, 1], b: [5, 1]
>>> print "id a: %s, id b: %s" % (id(a), id(b))
id a: 45930832, id b: 45930832
My guess, by seeing the id
of the instances above is because modifying an integer creates a new instance and re-assigns the new memory address to the variable. Is my suspicion correct? If so, does anyone know the "historical" decision of having ints behaving like this? Was it so programmers don't go nuts when int
variables are assigned to other variables? (I'm totally ok with that, by the way :-D )
As I said, this is mainly a curiosity. Thank you in advance!