65.9K
CodeProject is changing. Read more.
Home

Python Inline Increment/Decrement

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Nov 10, 2013

CPOL

1 min read

viewsIcon

11920

Python inline increment/decrement

Introduction

What seems inevitable while programming in C++ is the ++ operator (no wonder, having the language name in mind).

i++; ++i; i--; --i;

Inline -- and ++ constitute sort of a standard in quite a variety of languages, so let's get a grip on Python (2.7) as well. Move on to the snippet below:

A = range(0,10)
i = 0
print A[--i]

What is the output?

Having experience with C++/C#, etc. one might say it's an attempt to read at an out-of-bounds index. i would be decremented before accessing the list. However, in Python, a negative index corresponds to a position counted from the back of the list. A[-1] is the last element in the collection, which in this example equals 9. The above script prints 0, though. Why is that?

The reason is related to the fact that ++ and -- are neither operators in Python, nor is there any kind of syntactic sugar in it. Therefore --i should be split into two separate occurrences of - unary operator that returns negated number. It has no effect on the value of the variable i, though. The critical statement could be also written as:

print A[-(-i)]

What it really does is take the value of i and negate it twice without modifying the variable itself.

For instance, a typical C++ while-loop could become an infinite loop in Python:

i = len(some_collection)
while (--i > 0)
   ...

Finally, notice that i++ or i-- are not legal in Python.

Read on