1

Possible Duplicate:
Python: Behaviour of increment and decrement operators

>>> a=2
>>> ++a
2
>>> a++
Traceback (  File "<interactive input>", line 1
    a++
      ^
SyntaxError: invalid syntax
>>> ++a
2

why ++x is OK?

(I'm asking since someone at work habitually wrote ++i, which didn't do as (habitually) expected, but didn't throw an error either, so it took some time to find the bug.)

Community
  • 1
  • 1
Berry Tsakala
  • 15,313
  • 12
  • 57
  • 80

3 Answers3

8

It means +(+a), i.e. opposite to the meaning of -(-a) (although obviously in this case, the result is the same!)

See http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

It is equivalent to +(+a):

>>> +-2
-2
>>> -+2
-2
>>> --2
2
>>> ++++-2
-2
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

Possible duplicate of Python: Behaviour of increment and decrement operators.

Although I cannot find documentation for the exact reasoning for the operator I'll quote a portion from the accepted answer in the linked question that I believe is the case:

  • 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.
Community
  • 1
  • 1
PenguinCoder
  • 4,335
  • 1
  • 26
  • 37