Increment number by 1 in Python
In this tutorial, you will learn how to increment a number by 1 in Python.
If you are used to programming in languages like C++ and Java, you will be acquainted with using the increment operator (++) to increment the value of a number by 1.
However, you should now know that the increment operator does not exist for Python.
How else do you increment a number then?
In Python, instead of incrementing the value of a variable, we reassign it.
This can be done in the following ways:
Using the augmented assignment statement: increment integer in Python
You can use the += operator followed by the number by which you want to increment a value.
You can increment a number by 1 using the same as shown:
x=0 print(x) x+=1 print(x)
When you perform the above operation in Python, you are not simply incrementing the value but re-assigning it. The same is shown below for a better understanding:
x=0 print(id(x)) x+=1 print(id(x))
Remember, x+=1 works only as a standalone operator and cannot be combined with other operators (e.g.: x=y+=1, this is not allowed)
Using direct assignment:
You can simply increment a number by direct assignment as shown:
x=0 x=x+1 print(x)
Even in this method, the id of the variable changes, as you are assigning it with a new value and not simply incrementing.
x=0 print(id(x)) x=x+1 print(x) print(id(x))
140729511223664 1 140729511223696
Using the in-built function operator:
One of the many advantages of python is that it comes with many pre-defined functions. We can use such functions to increment a number without using even the arithmetic operator.
An example for incrementing a number by 1 using the operator function is as shown:
import operator x=0 x=operator.add(x,1) print(x)
However, this is preferable when you want scalability for your code. It is not very suitable when you want to just increment a single number by 1.
What happens if you use the increment operator (++) in Python?
If you use the pre-increment operator (++x), the parser interprets it as the identity operator (+), returning the value x. Thus, even though it throws no error, the value remains the same.
x=0 ++x print(x)
However, if you use the post-increment operator(x++), the parser interprets x as a variable followed by the arithmetic operator +, and thus expects another operand/variable after +. On finding + instead of an operand, it throws a syntax error as shown.
x=0 x++ print(x)
File "<ipython-input-3-f33a6b3667d6>", line 2 x++ ^ SyntaxError: invalid syntax
Another important thing to keep in mind is that you can only increment a number by another number. Don’t forget, trying to increment a character with an integer number will only give you errors.
To learn about character incrementing, click Ways to increment a character in Python