8.3. Python’s Fake Increment and Decrement Operators

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 incre- ments and decrements the numeric values in spam by 1 , respectively.

Other languages, such as C++ and JavaScript, have the ++ and – opera- tors for incrementing and decrementing. (The name “C++” itself reflects this; it’s a tongue-in-cheek joke that indicates it’s an enhanced form of the C language.) Code in C++ and JavaScript could have operations like ++spam or spam++ . Python wisely doesn’t include these operators because they’re notori- ously susceptible to subtle bugs (as discussed at https://softwareengineering .stackexchange.com/q/59880).

But it’s perfectly legal to have the following Python code:

>>> spam=42
>>> spam = --spam
>>> spam
42

The first detail you should 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 write code like this:

>>> spam = 42
>>> -spam
-42

It’s legal to have multiple unary negative operators in front of a value. Using two of them gives you the negative of the negative of the value, which for integer values just evaluates to the original value:

>>> spam = 42
>>> -(-spam)
42

This is a very silly operation to perform, and you likely won’t ever see a unary negation operator used twice in real-world code. (But if you did, it’s probably because the programmer learned to program in another language and 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:

>>> spam = 42
>>> +spam
42
>>> spam = -42
>>> +spam
-42

Writing +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. (That’s a lot of terms you might not be familiar with! You’ll learn more about operator overload- ing in Chapter 17.)

The + and - unary operators are only valid when in front of a Python value, not after it. Although spam++ and spam– might be legal code in C++ or JavaScript, they produce syntax errors in Python:

>>> spam++
File "<stdin>", line 1
spam++
^
SyntaxError: invalid syntax

Python doesn’t have increment and decrement operators. A quirk of the language syntax merely makes it seem like it does.