views:

7724

answers:

3

I am a newbie to Python. 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++?

+22  A: 

++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)

++count

Parses as

+(+count)

Which translates to

count

You have to use the slightly longer += operator to do what you want to do:

count += 1

I suspect the ++ and -- 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:

  • Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It's not a significant syntactic ambiguity, but it does exist.
  • Simpler language. ++ 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 += 1 into the inc instruction 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.
  • Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-incremend/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.
Chris Lutz
"The + operator is the "identity" operator, which does nothing." Only for numeric types; for other type it is an error by default.
newacct
Right. But then again, `++` and `--` should only be expected to work on numeric types.
Chris Lutz
Also, be aware that, in Python, += and friends are not operators that can be used in expressions. Rather, in Python they are defined as part of an "augmented assignment statement". This is consistent with the language design decision in Python to not allow assignment ("=") as an operator within arbitrary expressions, unlike what one can do in C. See http://docs.python.org/reference/simple_stmts.html#augmented-assignment-statements
Ned Deily
The unary `+` operator has a use. For decimal.Decimal objects, it rounds to current precision.
kaizer.se
Kaizer, that is an odd use for +. Any idea why Python does that for decimal.Decimal objects?
Ashwin
Chris, thanks so much for this detailed answer! I learnt a lot just by reading and understanding your explanation :-)
Ashwin
I'm betting on parser simplification. Note an item in [PEP 3099](http://www.python.org/dev/peps/pep-3099/), "Things that will Not Change in Python 3000": "The parser won't be more complex than LL(1). Simple is better than complex. This idea extends to the parser. Restricting Python's grammar to an LL(1) parser is a blessing, not a curse. It puts us in handcuffs that prevent us from going overboard and ending up with funky grammar rules like some other dynamic languages that will go unnamed, such as Perl." I don't see how to disambiguate `+ +` and `++` without breaking LL(1).
Mike DeSimone
A: 

In python ++(increment) or --(decrement) operators do not exist. In case of C++

int a = 5;
b = ++a;

b will be assigned the value 6. But, in python a++ will generate a syntax error as + or ++ is a binary operator and it needs a second operand. +a, ++a, +++++++a are all read by the python interpreter as +a

and doing something like this in python

a = 5
b = a ++ 5   // b is assigned 10
b = a +++ 5   // b is again assigned 10

So, ++ means simply two pluses.

detj
Your example is wrong. `b` would be assigned the value 5, not 6.
Chris Lutz
oops..yea! see fell into the gotcha!
detj
+20  A: 

When you want to increment or decrement, you typically want to do that on an integer. Like so:

b++;

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

Or simpler:

b += 1

Which will reassign b to 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 doesn't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.

Lennart Regebro
Excellent explanation!
Ber
I love your explanation of the why! :-)
Ashwin
That example is wrong (and you're probably confusing immutability with identity) - they have the same id due to some vm optimization that uses the same objects for numbers till 255 (or something like that). Eg (bigger numbers): >>> a = 1231231231231 >>> b = 1231231231231 >>> id(a), id(b) (32171144, 32171168)
ionelmc
The example is completely correct. You can redo my example with a = 1231231231231 and you will get the same result. The optimization you mention also exists, but is irrelevant in this case.
Lennart Regebro