integers in python are immutable and that is why post increment is not allowed and pre increment does not work.
And since integers are immutable, the only way to modify the, is by reassigning them like this:
x += 1
++
is not an operator. It is two +
operators. The +
operator is the identity operator, which does nothing which is why ++x
does not effect the variable.
To clarify:
++x
parses to +(+x)
Which translates to x
In practice the identiy operator +
is not used often. Here is the definition in the Python documentation:
The unary +
(plus) operator yields its numeric argument unchanged.
Here is an example I found in StackOverFlow where it is used with decimal rounding:
>>> from decimal import Decimal
>>> obj = Decimal('3.1415926535897932384626433832795028841971')
>>> +obj != obj # The __pos__ function rounds back to normal precision
True
>>> obj
Decimal('3.1415926535897932384626433832795028841971')
>>> +obj
Decimal('3.141592653589793238462643383')
Regarding post increment: Since this operator is not defined in Python, x++
gives a syntax error as the parser can't make sense of this expression.
IMHO the Pyton should give a WARNING when a programmer does ++
because it can lead to many errors on the part of C/C++/C# developers whose intent is to do a pre increment on a variable.