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.)

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+(+a) actually is not the opposite of -(-a), it's the same :-)
hence it's possible to write ------------a and +++++++++++++++++a. thanks.
3

It is equivalent to +(+a):

>>> +-2
-2
>>> -+2
-2
>>> --2
2
>>> ++++-2
-2

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.