In this short tutorial, we learn about how to increment in Python. We also look at why the unary increment/ decrement operator does not work in Python.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
Table of Contents - Python increment
- Why doesn’t the “++/--” operator work in Python?
- Python Increment
- Code and Explanation
- Python increment - Closing thoughts
Why doesn’t the “++/--” operator work in Python?
If you have used programming languages like C you have likely used the ++/ -- operator to increment or decrement a variable. However, if you have tried the same in Python you would receive an Invalid Syntax error.
Python does not treat variables the same way as C. Python uses names and objects and these values are immutable. The below examples would help you get a better understanding of this concept.
Let us assign the same integer value to multiple values and check the Id of the objects.
a = b = c = 1
print(id(a))
#Output - 1833296619824
print(id(b))
#Output - 1833296619824
print(id(c))
#Output - 1833296619824
As you can see since all the variables have the same values Python assigns the same value for all the objects. Python does this to increase memory efficiency.
Now if the value of one variable is changed, Python changes the value by reassigning the variable with another value.
a = b = c = 1
a = 2
print(id(a))
#Output - 1825080174928
print(id(b))
#Output - 1833296619824
print(id(c))
#Output - 1833296619824
Since the value of ‘a’ was changed, Python creates a new object and assigns it. However, the value of ‘b’ and ‘c’ remains the same.
In languages like C, each variable is given a value, if that value is incremented only that variable is affected. Since that is not the case in Python increment works differently.
The value needs to be reassigned and incremented by 1.
Python Increment:
Since ints are immutable, values need to be incremented and reassigned.
This can be done using a = a +1, but Python supports a += 1 as well.
Code and Explanation:
a = 1
a += 2
print(a)
#Output - 3
The above code shows how to increment values using Python increment. You could use the Id function before and after the values and check how the id changes after you have incremented the value.
Python increment - Closing thoughts:
Python increment can be quite easy to learn in case you are coming from another language. In case you are new to it, I would recommend you practice Python increment a few times.
And in case you are wondering where Python increments are used, they are used to count occurrences of a particular instance. Eg: Likes, log in, etc.
Top comments (1)
this meeting could have been an email