Is There ++ / — Operator In Python

Those of you who are familiar with programming languages probably know that there is an auto-increment ( ++ ) and auto-decrement ( — ) operator in arithmetic operators, it is very common when you’re writing loops. But the ++ and — operator might behave differently in Python operators, and it needs to be noticed.

Take a look at the Python code below.

>>> num = 1
>>> ++num
1
# Python doesn't know the ++ operator
>>> num
1

Similarly, Python does not recognize self decrement operators –.

>>> num = 1
>>> --num
1
>>> num
1

Attention! If you need a self increasing operation, you can only honestly use the variable assignment method such as num = num + 1.

Let’s look at below python example code.

>>> x = 1
>>>
>>> y = 1
>>> 
>>> id(x)
4427814032
>>>
>>> id(y)
4427814032
>>>
>>> x is y
True

As you can see, in Python, variables are based on content rather than on variable names. So if a variable’s content is 5, no matter what name you give to the variable, the ID of this variable is the same, which also means that a variable in Python can be accessed by multiple names.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.