Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ++ operator doing in Python? [duplicate]

Tags:

python

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?

like image 952
Jack Aidley Avatar asked Nov 28 '22 11:11

Jack Aidley


2 Answers

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.

like image 82
Games Brainiac Avatar answered Dec 01 '22 00:12

Games Brainiac


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.

like image 31
val Avatar answered Nov 30 '22 23:11

val