1

Possible Duplicate:
Why there are no ++ and — operators in Python?

This question may seem strange, but I'm wondering why is there no such operation in Python.

I know, x += 1 is almost as simple as x++, but still. There is such operation in most languages I'm familiar with (C, C++, Java, C#, JavaScript, PHP), but there isn't in Python.

Maybe it has something to do with the phylosophy of this language?

Community
  • 1
  • 1
Sergey
  • 47,222
  • 25
  • 87
  • 129

6 Answers6

5

To avoid preincrement, postincrement confusions and to keep things simple.

Also datatypes such as int, long are immutable. Meaning of ++, -- operators is to change the current datatype. Hence not supported.

After an increment operation the python object itself changes.

>>> a = int(10)
>>> b = a
>>> print id(a), id(b)
166744132 166744132
>>> a += 1
>>> print id(a), id(b)
166744120 166744132
>>> print a, b
11 10

Duplicate question as following which have more info :

Why are there no ++ and --​ operators in Python?

Behaviour of increment and decrement operators in Python

Community
  • 1
  • 1
Rajendran T
  • 1,513
  • 10
  • 15
  • 2
    Immutability isn't the problem: you're not changing the number `5`! (I seem to recall in some of the really early languages you could actually change the value of integers themselves. Obviously this is a bad thing.) It's just a design choice. – Katriel Jan 17 '12 at 22:30
4

While not directly related to Python, have a look at:

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

In short, yes, it is a language design decision.

Community
  • 1
  • 1
3

Quoth PEP-20:

There should be one – and preferably only one – obvious way to do it.

All the languages you mention inherit the operator from C, where the wide use of pointer arithmetics makes increment and decrement operations much more common. Having the shorthand wouldn't increase the expressivity of Python nowhere near as much, and there's really no other reason to add it to the language besides "C did it". (In and of itself not a very strong reason.)

millimoose
  • 39,073
  • 9
  • 82
  • 134
1

I think it is because avoid confusing side-effects

One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-incremend/decrement operators, and Python likes to eliminate language "gotcha"-s.

1

It is an issue of programming language structure. Increment operator is not quite often needed in Python. Instead, statements, like for i in range(0, 5), are used.

haberdar
  • 501
  • 5
  • 6
0

Frequently the "for i in range(0, 5):" is not good idea=) it only helps when you need numbers

zura
  • 106
  • 6