Python's Fake Increment and Decrement Operators
Mon 21 May 2018 Al Sweigart
In Python, you can increase the value of a variable by 1
or reduce it by 1
using the augmented assignment operators. The code spam += 1
and spam -= 1
increments and decrements the numeric values in spam
by 1
, respectively.
Other languages such as C++ and Java have the ++
and --
operators for incrementing and decrementing variables. (The name of C++ itself reflects this; the name is a tongue-in-cheek joke that indicates it's an enhanced form of the C language.) Code in C++ and Java could have ++spam
or spam++
. Python wisely doesn't include these operators; they are notoriously susceptible to subtle bugs.
However, it is perfectly legal to have the following Python code:
>>> spam = 42 >>> spam = ++spam >>> spam 42 >>> spam = --spam >>> spam 42
The first thing you notice is that the ++
and --
"operators" in Python don't actually increment or decrement the value in spam
. Rather, the leading -
is Python's unary negation operator. It allows you to have code like this:
>>> spam = 42 >>> print(-spam) -42It's legal to have multiple unary negative operators in front of a value. With two of them, you'd get the negative of the negative of the value, which for integer values just evaluates to the original value:
>>> print(--spam) 42 >>> --42 42
This is a quite silly thing to do, and you won't ever see a unary negation operator used twice in real-world code. (Though if you did, it's probably because the programmer learned to program in another language has just written buggy Python code!) There is also a +
unary operator. It evaluates an integer value to the same sign as the original value, which is to say, it does absolutely nothing:
>>> +42 42 >>> spam = -42 >>> print(+spam) # +spam is not the same as abs(spam) -42
Being able to write +42
(or ++42
) seems just as silly as --42
, so why does Python even have this unary operator? It exists only to complement the –
operator if you need to overload these operators for your own classes. (See the documentation for the __pos__
special method.)
The +
and –
unary operators are only valid when in front of a Python value, not after it. While spam++
and spam--
might be legal code in C++ or Java, they produce syntax errors in Python:
>>> spam++ File "<stdin>", line 1 spam++ ^ SyntaxError: invalid syntax
Python doesn't have increment and decrement operators, it's only a quirk of the langauge syntax that can make it seem like it does.