How do multiple assignments in a single line work?

Question:

I know that assignment is a statement in Python, i.e., it doesn’t evaluate to a value unlike an expression. How does the following line of code work in Python, then? Please explain what happens internally in the Python interpreter (lexing, parsing, formation of abstract syntax tree).

# this works
spam = eggs = 'ham'

# this doesn't work. Throws SyntaxError
spam = (eggs = 'ham')
Asked By: ajay

||

Answers:

why the first line above works while the second doesn’t?

It’s not about operator precedence. It’s a designated syntax. It cannot be “reconcilliated” by adding parenthesis.

Now for the full answer (as @Rob’s comments already indicate) see here and here.

Answered By: shx2
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.