Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignment and evaluation order in Python

What is the difference between the following Python expressions:

# First:  x,y = y,x+y  # Second:  x = y y = x+y 

First gives different results than Second.

e.g.,

First:

>>> x = 1 >>> y = 2 >>> x,y = y,x+y >>> x 2 >>> y 3 

Second:

>>> x = 1 >>> y = 2 >>> x = y >>> y = x+y >>> x 2 >>> y 4 

y is 3 in First and 4 in Second

like image 659
Rafael Carrillo Avatar asked Jan 04 '12 10:01

Rafael Carrillo


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.

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

What is multiple assignment in Python Class 12?

Multiple Assignment in PythonPython allows you to assign a single value to several variables simultaneously. For example − a = b = c = 1. Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location.


1 Answers

In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables. So,

x, y = y, x + y 

evaluates y (let's call the result ham), evaluates x + y (call that spam), then sets x to ham and y to spam. I.e., it's like

ham = y spam = x + y x = ham y = spam 

By contrast,

x = y y = x + y 

sets x to y, then sets y to x (which == y) plus y, so it's equivalent to

x = y y = y + y 
like image 67
Fred Foo Avatar answered Sep 23 '22 11:09

Fred Foo