3

Here's the snippet that I'm trying in the Python3 interpreter,

>>> x = y = 3
>>> x, y
(3, 3)
>>> x = y = 3
>>> x, y
(3, 3)
>>> x = y = y + 3
>>> x, y
(6, 6)
>>> x = y +=  3
  File "<stdin>", line 1
    x = y +=  3
           ^
SyntaxError: invalid syntax

I know that SyntaxError arises when the Python grammar doesn't support the expression, but I'm not able to figure out why exactly += can't be chained like =.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
Satwik
  • 1,281
  • 4
  • 18
  • 31

1 Answers1

1

As per the python docs -

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments.

Also,

the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

In python, assignment and augmented assignment are statements, not expressions, and thus cannot be used in complex expressions. For example, the following is valid C, but not valid in Python:

a += b += c

References:

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58