Click here to Skip to main content
15,886,199 members
Articles / All Topics
Technical Blog

Python Inline Increment/Decrement

Rate me:
Please Sign up or sign in to vote.
4.83/5 (3 votes)
10 Nov 2013CPOL1 min read 11.7K   1   1
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Neostrada Plus
Poland Poland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Question---i Pin
Leonel F Benitez30-Oct-15 19:55
Leonel F Benitez30-Oct-15 19:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.