I notice that a pre-increment/decrement operator can be applied on a variable (like ++count
). It compiles, but it does not actually change the value of the vari
Python does not have unary increment/decrement operators (--
/++
). Instead, to increment a value, use
a += 1
But be careful here. If you're coming from C, even this is different in python. Python doesn't have "variables" in the sense that C does, instead python uses names and objects, and in python int
s are immutable.
so lets say you do
a = 1
What this means in python is: create an object of type int
having value 1
and bind the name a
to it. The object is an instance of int
having value 1
, and the name a
refers to it. The name a
and the object to which it refers are distinct.
Now lets say you do
a += 1
Since int
s are immutable, what happens here is as follows:
a
refers to (it is an int
with id 0x559239eeb380
)0x559239eeb380
(it is 1
)int
object with value 2
(it has object id 0x559239eeb3a0
)a
to this new objecta
refers to object 0x559239eeb3a0
and the original object (0x559239eeb380
) is no longer refered to by the name a
. If there aren't any other names refering to the original object it will be garbage collected later.Give it a try yourself:
a = 1
print(hex(id(a)))
a += 1
print(hex(id(a)))