Postfix/Prefix Operators (++,--)

Chad Netzer cnetzer at mail.arc.nasa.gov
Fri Jun 6 02:29:15 EDT 2003


On Thu, 2003-06-05 at 22:49, hostmaster wrote:

> Python doesn't seems to support postfix/prefix operators (e.g. i++,
> --i).  Why?

Because it doesn't need them, and they cause a lot of problems in C and
C++.  Those languages need them because of the way their looping
constructs work.  One has to do lots of pointer arithmetic or indexing
in C/C++, where the postfix and prefix operators work well.  But they
can easily be used to make non-portable, undefined behavior happen in
the code.

Python has 'for' loops that automatically iterate over sequences, and so
doesn't really need the prefix and postfix operators.  It avoids their
complexity entirely.  They are rarely missed by those who have adjusted
to Python.

When you need to increment a variable, you can do this:

a += 1


When you need to iterate over a sequence, use a 'for' loop:

seq = ["a", "b", "c"]
for char in seq:
  print char

No incrementing necessary.

-- 

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)






More information about the Python-list mailing list