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?

2
  • 2
    I don't have 3.3 at hand, what error are you getting? Commented Oct 24, 2013 at 11:44
  • Apparently I was being some kind of muppet because when I try it again it works fine. Commented Oct 24, 2013 at 13:31

3 Answers 3

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.

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

1 Comment

@glglgl hi5 man. And rubyists say ruby gets to have all the fun :P
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.

Comments

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.

Comments