pythonoperatorsincrementdecrement

Behaviour of increment and decrement operators in Python


How do I use pre-increment/decrement operators (++, --), just like in C++?

Why does ++count run, but not change the value of the variable?


Solution

  • ++ 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: