0
Python: what is going on inside this for loop?
def f(n): x = y = 1.0 for i in range (1,n): x, y = y, x+y print(i) print(x) print (y) print("=================") return y/x print(f(3)) 1st iteration: i=1 x=1.0 y=2.0 2nd iteration: i=2 x=2.0 y=3.0 I do not understand the line x, y = y, x+y. I see this x+y expression, but it's not assigned to anything... so why does the x and y value increase?
3 Answers
+ 3
In expression x,y=y,x+y
y is assigned to x and x+y is assigned to y
+ 2
thats a special feature in python.
it allows multiple assignments in one row.
(at least it looks like)
x is assigned to y
y is assigned to x+y
+ 1
x, y = y, x+y:
The expression above represents tuple unpacking.
Consider this list.
L=[1,2,3,4,5]
If u wanted to assign members of the list to variables, u would use unpacking like this
x, y,z,a,b = L
Then x = 1, y=2 and so on.
This is also applicable to tuples
So for your example, expression on the right (y, x+y) is a tuple, you are simply assigning x and y the values of the tuple. So x=y and y=x+y