Behavior of ++ and Operators in Python



In C/C++, Java, etc., ++ and -- operators are defined as increment and decrement operators. In Python, they are not defined as operators.

Increment and Decrement Operators in Python

In Python, objects are stored in memory. Variables are just labels. Numeric objects are immutable. Hence, they can't be incremented or decremented. However, prefix ++ or -- doesn't give an error but doesn't perform either.

As Prefix 

In the following example, when have used prefix increment which does not raise an error -

x=5
print(++x)
print(--x)

Following is the output of the above code -

5
5

As Postfix

In the following example, we have used post increment, which raised an error -

x=10
print(x++)
print(x--)

Following is the output of the above code -

 File "/home/cg/root/45106/main.py", line 2
    print(x--)
             ^
SyntaxError: invalid syntax
Updated on: 2025-04-15T14:28:21+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements