Increment and Decrement Operators in Python?

PythonServer Side ProgrammingProgramming

Python does not have unary increment/decrement operator( ++/--). Instead to increament a value, use

a += 1

to decrement a value, use−

a -= 1

Example

>>> a = 0
>>>
>>> #Increment
>>> a +=1
>>>
>>> #Decrement
>>> a -= 1
>>>
>>> #value of a
>>> a
0

Python does not provide multiple ways to do the same thing .

However, be careful if you are coming from a languae like C, Python doesn’t have “variables” in the sense that C does, instead python uses names and objects and in python integers(int’s) are immutable.

Let’s understand it with an example−

>>> a =1
>>> print(id(a))
1919375088
>>> print(hex(id(a)))
0x726756f0

So what above statement means in python is: create an object of type int having value 1 and give the name a to it. The object is an instance of int having value 1 and the name a refers to it. The assigned name a and the object to which it refers are distinct.

Now lets increment a

>>> a +=1
>>> print(id(a))
1919375104
>>> print(hex(id(a)))
0x72675700

As int are immutable, python understand above statement as

  • Look up the object that a refers to (it is an int and id 0x726756f0)

  • Look up the value of object 0x726756f0 (it is 1).

  • Add 1 to that value (1+1 =2)

  • Create a new int object with value 2 (object with id 0x72675700).

  • Rebind the name a to this new object (0x72675700)

  • Now a refers to object 0x72675700 and the previous object (0x726756f0) is no longer refered to by the name a. If there aren’t any other names referring to the original object it will be garbage collected later.

So from above, you can understand when we do: a += 1

This will reassign a to a+1. That’s not an increment operator, because it does not increment a, but it reassign it.

Let’s understand above increment/decrement with some more example−

>>> a = b = c =1
>>> id(a)
1919375088
>>> id(b)
1919375088
>>> id(c)
1919375088
>>> #Above all have the same id
>>>
>>> # Now increment a
>>> a +=1
>>> id(a)
1919375104
>>> id(b)
1919375088
>>> id(c)
1919375088

From above you can understand we have a single object that a, b and c refers to (an int with id 1919375088)

On incrementing the value of a, now a is reasign to a+1 (id: 1919375104) and other b and c refers to same object (1919375088).

Also python does come up with ++/-- operator.

>>> a =1
>>> ++a
1
>>> --a
1
raja
Published on 02-May-2019 12:32:25
Advertisements