Advertisement
Advertisement


Python integer incrementing with ++


Question

I've always laughed to myself when I've looked back at my VB6 days and thought, "What modern language doesn't allow incrementing with double plus signs?":

number++

To my surprise, I can't find anything about this in the Python docs. Must I really subject myself to number = number + 1? Don't people use the ++/-- notation?

2020/04/24
1
822
4/24/2020 5:49:26 PM

Accepted Answer

Python doesn't support ++, but you can do:

number += 1
2010/04/13
1451
4/13/2010 7:46:57 PM


You can do:

number += 1
2010/04/13

Yes. The ++ operator is not available in Python. Guido doesn't like these operators.


The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++ is the next method of iterators.

2010/04/13

Take a look at Behaviour of increment and decrement operators in Python for an explanation of why this doesn't work.

Python doesn't really have ++ and --, and I personally never felt it was such a loss.

I prefer functions with clear names to operators with non-always clear semantics (hence the classic interview question about ++x vs. x++ and the difficulties of overloading it). I've also never been a huge fan of what post-incrementation does for readability.

You could always define some wrapper class (like accumulator) with clear increment semantics, and then do something like x.increment() or x.incrementAndReturnPrev()

2017/05/23

Here there is an explanation: http://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python

However the absence of this operator is in the python philosophy increases consistency and avoids implicitness.

In addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.

2010/04/13

Source: https://stackoverflow.com/questions/2632677
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]