Click here to Skip to main content
13,043,154 members (61,713 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 10 Nov 2013

Python Inline Increment/Decrement

, 10 Nov 2013
Rate this:
Please Sign up or sign in to vote.
Python inline increment/decrement


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


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


About the Author

Software Developer Neostrada Plus
Poland Poland
No Biography provided

You may also be interested in...

Comments and Discussions

Question---i Pin
Leonel F Benitez30-Oct-15 19:55
memberLeonel 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 10 Nov 2013
Article Copyright 2013 by pbalaga
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid