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 variable!
What is the behavior of the pre-increment/decrement operators (++/--) in Python?
Why does Python deviate from the behavior of these operators seen in C/C++?
++ is not an operator. It is two
+ operators. The
+ operator is the identity operator, which does nothing. (Clarification: the
- unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical
++ operator to work on strings.)
Which translates to
You have to use the slightly longer
+= operator to do what you want to do:
count += 1
I suspect the
-- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:
++countis ambiguous, as it could be
+operators) just as easily as it could be
++operator). It's not a significant syntactic ambiguity, but it does exist.
++is nothing more than a synonym for
+= 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimize
a += 1into the
incinstruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
++operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.
When you want to increment or decrement, you typically want to do that on an integer. Like so:
But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:
>>> b = 5 >>> a = 5 >>> id(a) 162334512 >>> id(b) 162334512 >>> a is b True
a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:
b = b + 1
b += 1
Which will reassign
b+1. That is not an increment operator, because it does not increment
b, it reassigns it.
In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.