how to understand difference between a+=1
and a=+1
in Python?
it seems that they're different. when I debug them in Python IDLE both were having different output.
how to understand difference between a+=1
and a=+1
in Python?
it seems that they're different. when I debug them in Python IDLE both were having different output.
Of course they are different - a+=1
sets value of a
to a + 1
and
a=+1
sets value of a
to 1:
>>> a = 2
>>> a += 1
>>> a
3
>>> a =+1
>>> a
1
Consider this:
a = 1
a = +1 # Assign Var a to value -> +1
a = +1 # Assign Var a to value -> +1
a = +1 # Assign Var a to value -> +1
a += 1
a += 1
a += 1
print(a) # -> 4
As you can see this a = +1
it's a variable assignment (as corrected by @adir abargil) , but a += 1
does add 1 to var a
.
This is the same as a = a+1, and is called: Assignment operator
a+=1
is a += 1
, where +=
is a single operator meaning the same as a = a + 1
.
a=+1
is a = + 1
, which assigns + 1
to the variable without using the original value of a
It really depends on the type of object that a
references.
For the case that a
is another int
:
The +=
is a single operator, an augmented assignment operator, that invokes a=a.__add__(1)
, for immutables. It is equivalent to a=a+1
and returns a new int object bound to the variable a
.
The =+
is parsed as two operators using the normal order of operations:
+
is a unary operator working on its right-hand-side argument invoking the special function a.__pos__()
, similar to how -a
would negate a
via the unary a.__neg__()
operator.=
is the normal assignment operatorFor mutables +=
invokes __iadd__()
for an in-place addition that should return the mutated original object.