Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

I notice that a pre-increment/decrement operator can be applied on a variable (like ++count). It compiles, but it does not actually change the value of the variable!

What is the behavior of the pre-increment/decrement operators (++/--) in Python?

Why does Python deviate from the behavior of these operators seen in C/C++?

2 Answers

0 votes
by (106k points)
edited by

When we try to do increment or decrement, we typically do that on an integer

Like as follows:


But when we deal with Python, so we see that integers are immutable in Python. That means you can't change them. 

b = 5

a = 5



a is b

Here, a and b above are actually the same objects. So if you increment a, you would also increment b. That's not what you want. So you have to reassign it as follows:-

b = b + 1


b += 1

The above codes will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.

So here, Python behaves differently, because Python is a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop.

To know more about this you can have a look at the following video tutorial:-

0 votes
by (33.1k points)
edited by

++ is not an operator. It is two + operators. The + operator is the identity operator, that does nothing. The + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.


Parses as


Which translates to


You have to use the slightly longer += operator to do what you want to do:

count += 1

I assume the ++ and -- operators were left out for consistency and simplicity.

Hope this answer helps you!

If you are looking for upskilling yourself in python you can join our Python Training and learn from the industry expert!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories