top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Increment/decrement operators in python?

+2 votes
1,518 views

I'm a relative newbie to python, and this NG, but it's certainly growing on me.

One thing I'm missing is the increment/decrement operator from C, ie x++, and its ilk. Likewise x += y.

Is there any way of doing this in Python?

posted Dec 5, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

When you want to increment or decrements, you typically want to do that on an integer. Like so:

b++

But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:

>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162334512
>>> a is b
True

a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:

b = b + 1

Or simpler:

b += 1

Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.

Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.

answer Dec 5, 2015 by Amit Kumar Pandey
Nice and proper explanation :)
0 votes

Quick answer:
x += y works. (Well, it should.)
x++ doesn't.

answer Dec 5, 2015 by Garima Jain
Similar Questions
+2 votes

Starting on any day/date, I would like to create a one year list, by week (start date could be any day of week). Having a numerical week index in front of date, ie 1-52, would be a bonus.
ie, 1. 6/4/2013
2. 6/11/2013
3. 6/18/2013....etc to # 52.

And to save that result to a file. Moving from 2.7 to 3.3

0 votes

Which one will be faster in Java, Increment operator or Decrement operator?

a) for(int i = 0; i < 1000; i++) {}    
b) for(int i = 1000; i > 0; i--) {}
...