1

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.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
Lion14706
  • 47
  • 3
  • 3
    `(plus)1` is just `1` (positive 1), so `a=+1` is just `a=1`. `(plus)` should be `+`, but stackoverflow won't let me start my comment off with `+1` :( – Aplet123 Dec 24 '20 at 16:50
  • 2
    One is `a += 1`, augmented assignment equivalent to `a = a + 1`, the other is `a = +1`, assignment and a unary plus equivalent to `a = 1`. Unless a was zero they'll be different – jonrsharpe Dec 24 '20 at 16:51
  • 3
    When you ask about some behavior that is unexpected, please provide the necessary code and input data to reproduce the exact isssue, and what you expected to happen instead. `a += 1` _alone_ will give a `NameError`. – Pac0 Dec 24 '20 at 16:53

4 Answers4

4

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
Arkadiusz Drabczyk
  • 10,250
  • 2
  • 20
  • 35
4

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


Other Stack Overflow Answers

Documentations

MarianD
  • 11,249
  • 12
  • 32
  • 51
Federico Baù
  • 3,772
  • 4
  • 18
  • 27
  • Yes you right, it define the variable again, I wanted to explain that but in the rush I wrote that does nothing (for a beginner eye seems it does nothing, but is wrong) ! I edit now :) – Federico Baù Dec 24 '20 at 17:18
2

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

MegaIng
  • 6,933
  • 1
  • 21
  • 34
1

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:

  1. + 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.
  2. = is the normal assignment operator

For mutables += invokes __iadd__() for an in-place addition that should return the mutated original object.