views:

226

answers:

2

Possible Duplicate:
Python: Behaviour of increment and decrement operators

Hi, I've tried this.

++num

and the num doesn't change at all, always show the value when initialized

if I change ++num to num+=1 then it works.

So, my question is how that ++ operator works?

+17  A: 

There isn't a ++ operator in python. You're applying unary + twice to the variable.

Nick T
+9  A: 

Answer: there is no ++ operator in Python. += 1 is the correct way to increment a number, but note that since integers and floats are immutable in Python,

>>> a = 2
>>> b = a
>>> a += 2
>>> b
2
>>> a
4

This behavior is different from that of a mutable object, where b would also be changed after the operation:

>>> a = [1]
>>> b = a
>>> a += [2]
>>> b
[1, 2]
>>> a
[1, 2]
Seth Johnson
I don't see how the += behavior you showed is different from any other language with a += operator that translates `x += c` to `x = x + c` Even if the type was mutable, += always creates a new instance instead of mutating.
Davy8
+1 for more informative than the guy with the faster trigger-finger
BlueRaja - Danny Pflughoeft
@Davy8: `+=` does *not* make a new object if it's mutable -- only when it isn't.
Daenyth
Interesting... so in Python `x += y` does not translate to `x = x + y`. That seems counterintuitive to me, but I haven't been bitten by it yet.
Davy8
And you are correct, I just tested it. If I do `a += [2]` then I get the result described, but if I do `a = a + [2]` then `b` remains `[1]` and `a` is `[1, 2]`.
Davy8
I don't understand how the example demonstrates integer immutability. If I do `int a, b; a = 2; b = a; a += 2` in C with its presumably mutable integers, I get the exact same result.
Nick T
Actually, `x += y` *can* translate into `x = x + y` if `x` is an object with `__add__` overloaded but not `__iadd__`.
Mike DeSimone
@Nick: in Python, effectively every object is a reference. It's different from C.
Seth Johnson
If it transparently works the same, how is it different? Yeah, I could use pointers with the C code, but the "default" mechanism of variables function similarly.
Nick T