Jay F.
Jay F.

Reputation: 33

Clarification of What is Happening in Python For Loop

I am working through the Coursera Python course and am a bit turned around with some shorthand.

    x = 0
    y = 1
    for i in range(40):
    x, y = y, x + y
    print y

I understand it is adding X and Y and assigning the new value to Y but don't quite follow the x, y = y, x + y notation. I searched the docs without much success.

Upvotes: 1

Views: 54

Answers (4)

outoftime
outoftime

Reputation: 765

This feature called sequence packing\unpacking. It consist of two parts: packing expression of right side near = sign and then unpacking it into variables from the right.

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

Upvotes: 0

gaganso
gaganso

Reputation: 3011

The comma indicates that the right hand side is a tuple containing y and x+y. The comma on the left indicates that the unpacking should be done.

So x gets the value of y and y gets the value of x+y

You can check how the references change simultaneously here

After opening the link, click on visual execution and keep clicking on forward.

Upvotes: 1

kcborys
kcborys

Reputation: 316

This assigns y to x and x+y to y, but notice that it does it at the "same time". If you tried something like

x = y
y = x + y
print y

you would get an entirely different result.

Upvotes: 0

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

x, y = y, x + y

x is assigned the value of y
and y is assigned the value of x + y

Upvotes: 1

Related Questions