ajay
ajay

Reputation: 9680

How do multiple assignments in a single line work?

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')

Upvotes: 7

Views: 6093

Answers (1)

shx2
shx2

Reputation: 64288

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.

Upvotes: 10

Related Questions