Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How does 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')
like image 956
ajay Avatar asked Nov 20 '13 05:11

ajay


People also ask

Can we do multiple assignments in Python?

Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.

Can I assign 2 variables at once?

Multiple variable assignment is also known as tuple unpacking or iterable unpacking. It allows us to assign multiple variables at the same time in one single line of code. In the example above, we assigned three string values to three variables in one shot. As the output shows, the assignment works as we expect.

Is multiple assignment faster in Python?

Multiple assignment is slower than individual assignment. For example "x,y=a,b" is slower than "x=a; y=b". However, multiple assignment is faster for variable swaps. For example, "x,y=y,x" is faster than "t=x; x=y; y=t".


1 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.

like image 80
shx2 Avatar answered Sep 21 '22 23:09

shx2