4

Python doesn't support C-style ++a increment but, to my surprise, it doesn't complain either leading to me being temporarily baffled as to why my loop wasn't working.

Trying a few things (having first initialised with a=0) I find that a++ and a-- produce a syntax error, but ++a doesn't. While --a produces a syntax error in Python 3.3 but not in Python 2.7.

What's going on? Why doesn't ++a give an error? Why does --a not give an error in 2.7 but does give an error in 3.3?

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
Jack Aidley
  • 19,439
  • 7
  • 43
  • 70

3 Answers3

17

Take a look at this console session:

>>> a = 10
>>> ++a
10
>>> +a
10
>>> -a
-10
>>> --a
10

Basically, ++a == +(+(a)), and --a == -(-(a)). This one's to hit the concept home (and for fun):

>>> ++++++++++a
10

The following code sample serves no purpose other than to show you how much fun python is:

>>> +-+-+a
10

With something like this, you can make ASCII art that runs.

If you want to increment you do it like so: a += 1. And --a works in Python 2 and 3.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
12

Short answer: it calls the __pos__ method twice. Consider for instance:

>>> class A(object):
...     def __init__(self, x):
...         self.x = x
...     def __pos__(self):
...         return A(2 * self.x)
...     def __repr__(self):
...         return 'A(%s)' % self.x
... 
>>> a = A(1)
>>> a
A(1)
>>> +a
A(2)
>>> ++a
A(4)
>>> +++a
A(8)

For integers, as +x returns x, it does basically nothing.

val
  • 8,459
  • 30
  • 34
0

No, in Python (both 2.x and 3.x), using ++var will return the same value of the variable as it was previously, provided that the variable's value was actually a number. And using var++ will raise an exception.

Also, in Python the ++var operation's behavior is not as same as some other languages, like PHP, JS, C++, where ++var actually means that you're to increment the variable's value by 1. But in Python, to increment, you must use something like var = var + 1 or var += 1 or it will not work.

Akshat Tripathi
  • 321
  • 2
  • 12