Click here to Skip to main content
Click here to Skip to main content

Python Inline Increment/Decrement

, 10 Nov 2013
Rate this:
Please Sign up or sign in to vote.
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)

About the Author

pbalaga
Software Developer Neostrada Plus
Poland Poland
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 10 Nov 2013
Article Copyright 2013 by pbalaga
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid